使用swc-loader加快构建需要10000+分包的逆天项目!!!!

292 阅读1分钟

背景

项目编译的文件达到了10000+,启动速度巨慢,删除文件还不好进行删除,最近看到了rspack内置的swc-loader,它可以替换缓慢的babel-loader,于是看看能不能对他进行一下优化。

node版本:14 webpack:4.x

image.png

安装swc-loader

npm i -D @swc/core swc-loader

直接使用swc-loader替换babel-loader

{
    test: /\.js$/,
    include: [resolve('src')],
    exclude: /node_modules/,
       use: [
        'cache-loader',
        'thread-loader',
        {
            loader: "swc-loader",
            options: {
                jsc: {
                    parser: {
                        syntax: 'ecmascript',
                        jsx: true
                    }
                },
                sourceMaps: true,
            }
        }
    ]
}

于是乎,产生了下面问题,搜索文档发现,swc-loader需要开启装饰器的编译 image.png

替代之后

{
    test: /\.js$/,
    include: [resolve('src')],
    exclude: /node_modules/,
       use: [
        'cache-loader',
        'thread-loader',
        {
            loader: "swc-loader",
            options: {
                jsc: {
                    parser: {
                        syntax: 'ecmascript',
                        decorators: true,
                        jsx: true
                    }
                },
                sourceMaps: true,
            }
        }
    ]
}

问题并没有得到解决,只能是想到了组合使用的方式,babel先将装饰器的部分编译了之后再交给swc-loader

完整配置

{
    test: /\.js$/,
    include: [resolve('src')],
    exclude: /node_modules/,
       use: [
        'cache-loader',
        'thread-loader',
        {
            loader: "swc-loader",
            options: {
                jsc: {
                    parser: {
                        syntax: 'ecmascript',
                        jsx: true
                    }
                },
                sourceMaps: true,
            }
        },
        {
            loader: 'babel-loader',
            options: {
                plugins: [
                    ['@babel/plugin-proposal-decorators', { legacy: true }],
                    '@babel/plugin-transform-runtime'
                ]
            }
        }
    ]
}

最后来看结果,大致对比了一下,编译和打包速度都能快20%左右。

PS: 博主第一次发笔记文章,也只是个刚毕业没多久的小白,swc-loader的配置文档看的不是太明白,只能想到这种方式,也想请教一下有什么方式能更直观的对比出效率的提升。