如何配置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
相关产品推荐
相关产品推荐

