使用 UglifyJS2 和 gulp 插件时保留许可证注释

x29*_*29a 7 uglifyjs uglifyjs2 gulp webpack gulp-uglify

在这个项目中,我使用gulp-uglify版本 3.0.1,我想在输出中保留包含许可证文本的注释。

在项目页面上指出

Most of the minify options from the UglifyJS API are supported.
Run Code Online (Sandbox Code Playgroud)

这个答案展示了如何将minify 选项传递给插件。

UglifyJS 自述文件中指出,为了保留许可证文本

You can pass --comments to retain certain comments in the output. By default it will keep JSDoc-style comments that contain "@preserve", "@license" or "@cc_on" (conditional compilation for IE)
Run Code Online (Sandbox Code Playgroud)

所以我尝试了:

.pipe(uglify({
    mangle: true,
    output: {
        beautify: true,
        comments: "all"
    }
}))
Run Code Online (Sandbox Code Playgroud)

但由于即使指定也"all"不会产生任何许可证归属注释,我假设 minify 选项的comments行为与命令行参数不同--comments

我也尝试了这里的preserveComments发现,但只会生成:

[13:37:42] GulpUglifyError: unable to minify JavaScript
Caused by: DefaultsError: `preserveComments` is not a supported option
Run Code Online (Sandbox Code Playgroud)

有没有办法通过插件实现命令行参数的gulp-uglify建议?如果不可能,我可以使用webpack 插件吗?

通过指定正则表达式可以解决此问题,但如果可能的话,我想直接使用 UglifyJS 的功能。此外,它也不保留这样的许可证头。

Jer*_*nch 4

我有同样的问题。我注意到建议的UglifyJS 评论文档

您可以传递--comments all以保留所有注释,或传递有效的 JavaScript 正则表达式以仅保留与此正则表达式匹配的注释。例如--comments /^!/将保留类似的评论/*! Copyright Notice */

所以我尝试了“ comments: /^!/”:

.pipe(uglify({
    mangle: true,
    output: {
        beautify: true,
        comments: /^!/
    }
}))
Run Code Online (Sandbox Code Playgroud)

我现在在生成的丑化代码中看到了版权注释。