webpack - 支持ts(x)

898 阅读1分钟

新建了一个项目,使用react webpack搭建,开发使用纯ts(x)

在引入antd之后,为了tree shaking又配置了babel-plugin-importwebpack配置如下:

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-react'],
            plugins: [
                '@babel/plugin-transform-runtime',
                ['import', {
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    style: 'css',
                }],
            ]
        }
    }
}

出于个人习惯,没用babelrc

但这个配置的testts(x)是不匹配的,所以单独又写了一个配置:

{
    test: /\.tsx?$/,
    exclude: /node_modules/,
    use: ['ts-loader', {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-react'],
            plugins: [
                '@babel/plugin-transform-runtime',
                ['import', {
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    style: 'css',
                }],
            ]
        }
    }]
}

这个配置编译是能通过,但babel-plugin-importtree-shaking失效了;之所以这么说,是因为当我把文件都改成js(x)时,符合剪枝的预期。

猜测是ts-loader配置有问题,但两个雷同配置本身就有点不爽,索性这次解决这个问题,思路是基于babel-loader配置,增加对ts的支持。

过程也不是特别复杂,直接上结果:

npm i -D @babel/preset-typescript

配置一个loader项目就可以了:

{
    test: /\.[jt]sx?$/,
    exclude: /node_modules/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/preset-react', '@babel/preset-typescript'],
            plugins: [
                '@babel/plugin-transform-runtime',
                ['import', {
                    libraryName: 'antd',
                    libraryDirectory: 'es',
                    style: 'css',
                }],
            ]
        }
    }
}

以上。