webpack 转译TS支持方案

1,804 阅读1分钟

1. ts-loader + babel-loader + fork-ts-checker-webpack-plugin

  • ts-loader 会调用 typescripttypescript 运行时会去读取本地的 tsconfig.json 文件。
  • 默认情况下ts-loader 会进行 转译 和 **类型检查,**每当文件改动时,都会重新去 转译类型检查,当文件很多的时候,就会特别慢,影响开发速度。所以需要使用 fork-ts-checker-webpack-plugin ,开辟一个单独的线程去执行类型检查的任务,这样就不会影响 webpack 重新编译的速度
// webpack.config.js
const path = require('path');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    context: process.cwd(), // to automatically find tsconfig.json
    entry: {
        main: main
    },
    output: {
        path: path.join(process.cwd(), 'dist'),
        filename: '[name].js',
    },
    plugins: [
        new ForkTsCheckerWebpackPlugin({
            async: false,
            useTypescriptIncrementalApi: true,
            memoryLimit: 4096
        }),
        new HtmlWebpackPlugin({
            hash: true,
            inject: true,
            template: 'src/index.html',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
        }),
    ],
    module: {
        rules: [
            {
                test: /.tsx?$/,
                use: [
                  	'babel-loader',
                    { loader: 'ts-loader', options: { transpileOnly: true } } // ts-loader 只做转义不做静态检查
                ],
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    }
};

2. babel-loader + @babel/perset-typescript

  • webpac编译时会调用 babel-loader 配置,不会调用 typescript (tsc),只会转义不会做静态检查
  • 不配置 tsconfig.json 会享受不到vscode的静态检查,建议配置 tsconfig.json
// webpack.config.js
rules: [
  {
    test:/\.(tsx?|jsx?)$/,
    use:'babel-loader'
  }
]
// .babelrc
{
    "presets": [
         "@babel/preset-env",
         "@babel/preset-typescript"
    ]
}
  • 编译时如果添加静态检查,需要单独开启一个脚本支持检查任务

    "scripts": {
         // 单独开启一个脚本执行
        "type-check": "tsc --watch",
      },
    
    {
      "compilerOptions": {
        // 不生成文件,只做类型检查
        	"noEmit": true,                      
      }
    }
    

Q&A

使用了ts-loader 后,为什么还要需要 babel-loader

相同点:

​ 可以支持转义typescriptes5es3

不同点:

babel-loader 相对于ts-loader,拥有非常丰富的生态,例如在低版本的js环境中可以添加垫片、摇树优化、按需加载等等

有了ts的静态检查,为什么还需要ESLint

​ ts的静态检查的重点是类型检查eslint 重点在代码风格的检查,这在多人协作的项目中,保持项目的健康向好发展,提升开发时的效 率、代码的可理解性以及可维护性时非常重要