webpack5 + vue2.7
主要依赖包
- webpack@5.74.0
- webpack-cli@4.10.0
- webpack-dev-server@4.11.0
- vue@2.7.10
- typescript@4.8.3
- vue-loader@15.10.0
- @babel/core@7.17.5
- @babel/preset-env@7.16.11
- babel-loader@8.2.3
- html-webpack-plugin@5.5.0
- mini-css-extract-plugin@2.5.3
- less@2.13.1
- less-loader@7.3.0
- css-loader@6.6.0
下面列出主要的配置。
Babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
chrome: 84
}
},
],
]
}
webpack.config.js
...
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use:[
'babel-loader',
{
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],// 重要
transpileOnly: true,// 重要
happyPackMode: false,
}
}
]
},
]
},
resolve: {
extensions: ['.ts','.tsx', '.js','.vue'],
...
}
...
tsconfig.json (同vue-cli 生成的,修改jsx:"react")
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "react", // preserve会报错,不知道vue-cli怎么做的
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
小结
主要是ts 和tsx 的处理。不用ts的情况下, 网上说用babel 的transform-vue-jsx 等插件完成jsx解析。
由于ts-loader 会处理jsx语法,在tsconfig.json 中配置 compilerOptions.jsx = 'react' 即可,设preserve会报错。要注意ts-loader 配置,appendTsSuffixTo 和 transpileOnly,不配置的话会报错。
因此,这里 babel 的配置很干净,没有处理有关 jsx 的 preset 和 plugin。
若报错webpack-env的类型问题,则npm i @types/webpack-env即可。
后续
使用swc 替换ts-loader 加速构建webpack-vue-tsx项目_JA+的博客-CSDN博客
其他
有的文章说:“ts-loader编译太慢!我不用 ts-loader!” 可以用 babel 配合 @babel/preset-typescript 预设来解析ts即可。(试了一下没成功)
通过
vue inspect > output.js
命令导出vue-cli 的webpack配置,用于参考。