You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Rollup与Terser移除Web应用JS Bundle Sourcemap中的注释

解决Rollup + Terser生成无注释Sourcemap的问题

问题场景

需要配置Rollup及Terser插件,为Web应用生成不含源码注释的压缩JS Bundle和对应Sourcemap。现有配置可正常生成main.bundle.js和main.bundle.js.map,但尝试通过terser({sourceMap: {comments: false}})配置移除注释时,出现错误:[!] (plugin terser) Error: Minify worker stopped with exit code 1。

现有Rollup配置:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';

export default [
    {
        input: './src/js/main.js',
        output: {
            file: './dist/main.bundle.js',
            format: 'iife',
            name: 'mainjs',
            sourcemap: true
        },
        treeshake: {
            moduleSideEffects: false
        },
        plugins: [
            resolve(),
            terser()
        ]
    }
]

尝试的错误Terser配置:

terser({
    sourceMap: {
        comments: false
    }
})

错误原因

Terser不存在sourceMap.comments这个配置项,无效参数导致Terser Worker启动失败。要移除Sourcemap中的注释,需调整Terser的注释过滤规则,配合Rollup的Sourcemap配置实现。

正确配置方案

修改后的完整Rollup配置如下:

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';

export default [
    {
        input: './src/js/main.js',
        output: {
            file: './dist/main.bundle.js',
            format: 'iife',
            name: 'mainjs',
            sourcemap: true
        },
        treeshake: {
            moduleSideEffects: false
        },
        plugins: [
            resolve(),
            terser({
                // 移除压缩包中所有注释,同时让Sourcemap不包含源码注释
                format: {
                    comments: false
                },
                sourceMap: {
                    // 不将原始源码内容嵌入Sourcemap,仅保留位置映射,进一步避免注释混入
                    includeSources: false
                }
            })
        ]
    }
]

配置说明

  • format.comments: false:彻底清除压缩后Bundle中的所有注释,同时Terser生成Sourcemap时不会将源码注释写入map文件。
  • sourceMap.includeSources: false:取消将原始源码内容嵌入Sourcemap,仅保留文件名和代码位置映射,既减小Sourcemap体积,也从根源避免注释被包含。

如果需要保留特定注释(如版权声明),可将format.comments设为过滤函数:

format: {
    comments: (node, comment) => {
        // 仅保留以@license或@preserve开头的注释
        return /@license|@preserve/.test(comment.value);
    }
}

内容的提问来源于stack exchange,提问作者SpechtacularDave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:34:59