webpack5 + vue2.7
下面列出主要的配置。
- module.exports = {
- presets: [
- [
- '@babel/preset-env',
- {
- targets: {
- chrome: 84
- }
- },
- ],
- ]
- }
- ...
- 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'],
- ...
- }
- ...
- {
- "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配置,用于参考。