使用 Rspack 与 SWC 加速 VSCode 插件打包:从 5 秒到 200 毫秒的优化之路

534 阅读1分钟

项目地址:github.com/jackiotyu/g…

打包效果对比

  1. 使用webpack5打包 image.png
  2. 使用rspack打包 image.png

可以看到构建时间已经极大缩短了,构建产物的体积也缩减了

图上查看文件资源分类和大小的vscode插件是 Size Tree

优化过程

首先是直接按官方文档迁移 webpack,新建一个rspack.config.js,对比webpack的配置主要修改如下

// rspack.config.js
/** @type {import('@rspack/cli').Configuration} */
const extensionConfig = {
    ...
    output: {
        // 从libraryTarget: 'commonjs2',修改为下面的配置
        library: {
            type: 'commonjs2',
        },
    },
    module: {
        rules: [
            {
                // 从 loader: 'ts-loader', 修改为以下配置
                test: /\.ts$/,
                exclude: [/node_modules/],
                loader: 'builtin:swc-loader',
                options: {
                    jsc: {
                        parser: {
                            syntax: 'typescript',
                        },
                    },
                },
                type: 'javascript/auto',
            },
        ],
    },
};

module.exports = extensionConfig;

修改后尝试打包,结果如下

image.png 打包时间优化了,但是产物体积有点不正常,使用webpack打包时只有130多KB。

不过之前用ts-loader时,其实配合了tslib优化,把很多重复的辅助函数整合到一起导入了

这里怀疑是swc-loader没有使用tslib

image.png 搜索一下打包后的代码,果然发现了很多重复的辅助函数

swc官方文档尝试使用关键词helper搜索相关配置 image.png image.png

swc.rs/docs/config…

看文档配置,这个选项是用来缩减产物体积的,可以替代tslib的效果

swc-loader的选项上添加上externalHelpers: true,安装@swc/helpers,再重新打包

image.png 完成🎉🎉🎉

完整配置

// rspack.config.js
'use strict';
const path = require('path');
/** @type {import('@rspack/cli').Configuration} */
const extensionConfig = {
    target: 'node',
    mode: 'none',
    entry: './src/extension.ts',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'extension.js',
        library: {
            type: 'commonjs2',
        },
    },
    externals: {
        vscode: 'commonjs vscode',
    },
    resolve: {
        tsConfig: {
            configFile: path.resolve(__dirname, 'tsconfig.json'),
        },
        extensions: ['...', '.ts'],
    },
    module: {
        rules: [
            {
                test: /\.ts$/,
                exclude: [/node_modules/],
                loader: 'builtin:swc-loader',
                options: {
                    jsc: {
                        parser: {
                            syntax: 'typescript',
                        },
                        externalHelpers: true,
                    },
                },
                type: 'javascript/auto',
            },
        ],
    },
    devtool: 'nosources-source-map',
    infrastructureLogging: {
        level: 'log',
    },
    optimization: {
        usedExports: true,
        innerGraph: true,
    }
};
module.exports = extensionConfig;