ts项目搭建
作者:互联网
1.创建文件夹&项目初始化
npm init -y
2.下载
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader
npm i -D @babel/core @babel/preset-env babel-loader core-js
npm i -D css-loader less less-loader style-loader html-webpack-plugin clean-webpack-plugin
3.创建src根文件夹和index.html(作为编译模板)index.ts(作为入口文件)
4.使用一下命令创建tsconfig.json
tsc --init
5.配置package.json
"main":"./src/index.ts", //要修改正确的入口文件哦"scripts": { "start":"webpack-dev-server", //也可以这样配置 "start":"webpack-dev-server --open Chrome"
// 或者这样的"start":"webpack-dev-server --open 'Google Chrome'"
// 看人家这样配置没报错,我的报错,故用最简单的配置了(苦笑)
"build":"webpack" },"devDependencies": { "@babel/core": "^7.18.13", "@babel/preset-env": "^7.18.10", "babel-loader": "^8.2.5", "clean-webpack-plugin": "^4.0.0", "core-js": "^3.25.0", "css-loader": "^6.7.1", "html-webpack-plugin": "^5.5.0", "less": "^4.1.3", "less-loader": "^11.0.0", "postcss-loader": "^7.0.1", "postcss-preset-env": "^7.8.0", "style-loader": "^3.3.1", "ts-loader": "^9.3.1", "typescript": "^4.8.2", "webpack": "^5.74.0", "webpack-cli": "^4.10.0", "webpack-dev-server": "^4.0.0" }
//贴上我下载的依赖包版本
6.配置webpack.config.js
const path = require('path'); //引入html插件 const HTMLWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin') module.exports = { "mode": "development", //指定入口文件 entry: "./src/index.ts", //指定打包文件所在的目录 output: { //指定打包文件的目录 path: path.resolve(__dirname, './dist'), //打包后文件的文件 filename: 'bundles.js' }, devServer: { static: { directory: path.join(__dirname, './'), watch: true } }, //指定webpack打包时要是用的模块 module: { //指定要加载的规则 rules: [ { // test指定是规则生效的文件 test: /\.ts$/, use: [{ //指定预加载器 loader: "babel-loader", //配置babel options: { //配置预定义的环境 presets: [ [ //制定环境插件 "@babel/preset-env", //配置信息 { //要兼容的浏览器 targets: { "chrome": "104" }, //指定corejs版本 "corejs": "3", //使用corejs的方式usage表示按需加载 "useBuiltIns": "usage" } ] ] } }, 'ts-loader'], //要排除的文件 exclude: /node-modules/ },{ test:/\.less$/, use:[ "style-loader", "css-loader", //引入postcss { loader:"postcss-loader", options:{ postcssOptions:{ plugins:[ [ "postcss-preset-env", { browsers:'last 2 versions' } ] ] } } }, "less-loader" ] } ] }, //配置webpack插件 plugins: [ //自动生成html文件 并引入相关的资源 new HTMLWebpackPlugin({ title: 'project', //模板选项 根据模板生成html文件 template: "./src/index.html" }), new CleanWebpackPlugin() ], //用来设置引用的模块 resolve: { extensions: ['.ts', '.js'] } }
7.写点东西看看效果
src/index.html <div id="main"></div> src/style/index.less //设置变量 @bg-color: #b7d438; @p-color:pink; // 清除默认样式 *{ padding: 0; margin: 0; box-sizing: border-box; } //主窗口样式 #main{ width: 360px; height: 420px; background-color:@p-color; } // 引入样式文件 //引入样式 import './style/index.less'
执行 npm start
虽然很简单,但仍出现未曾料想的错误,诸多波折,记录一下,自己要不断加油!!!
标签:项目,babel,less,ts,loader,webpack,html,搭建 来源: https://www.cnblogs.com/guohuimin/p/16629694.html