webpack构建ts+vue3
一、构建项目目录
如图:
shim.d.ts 这个文件用于让ts识别.vue后缀的 后续会说
并且给 tsconfig.json 增加配置项
"include": ["src/**/*"]
二、基础构建
安装依赖
安装如下依赖:
npm install webpack -D
npm install webpack-dev-server -D
npm install webpack-cli -D
修改 package.json 的启动服务和打包命名
{"scripts": {"build": "webpack","dev": "webpack-dev-server"}
}
编写 webpakc.config.js 配置文件
const {Configuration} = require('webpack')
const path = require('node:path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {VueLoaderPlugin} = require('vue-loader')
const CssExtractPlugin = require('mini-css-extract-plugin')
/*** @type {Configuration}*/
const config = {mode:'development',entry:'./src/main.ts', // 入口文件output:{path:path.resolve(__dirname,'dist'), //生成目录filename:'[chunkhash].js' ,//打包之后的文件clean:true //清空打包的结果},stats:'errors-only',plugins:[new HtmlWebpackPlugin({template:'./index.html'}),new VueLoaderPlugin(),new CssExtractPlugin()], //webpack的插件都是class 都需要newmodule:{rules:[{test:/\.ts$/,use:{loader:'ts-loader', // 处理ts文件options:{appendTsSuffixTo:[/\.vue$/]}}},{test:/\.vue$/,use:'vue-loader',},{test:/\.css$/,use:[CssExtractPlugin.loader,'css-loader'], //从右向左解析},{test:/\.less$/,use:[CssExtractPlugin.loader,'css-loader','less-loader'], //从右向左解析}]},optimization:{splitChunks:{cacheGroups:{moment:{name:'moment',chunks:'all',test:/[\\/]node_modules[\\/]moment[\\/]/},common:{name:'common',chunks:'all',minChunks:2 //它的引用次数大于2个就会被分割出来}}}}
}module.exports = config
这时候就能正常使用了