Search code examples
webpackgulpuglifyjsgulp-uglifyuglifyjs2

Keep license comments when using UglifyJS2 with gulp plugin


In this project i am using gulp-uglify version 3.0.1 and i want to preserve comments containing license texts in the output.

On the projects page it is stated that

Most of the minify options from the UglifyJS API are supported.

and this answer shows how to pass the minify options to the plugin.

In the UglifyJS Readme it is stated that in order to preserve license texts

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)

So i tried:

.pipe(uglify({
    mangle: true,
    output: {
        beautify: true,
        comments: "all"
    }
}))

But since even specifying "all" results in no license attribution comments, i assume that the minify option comments behaves differently then the commandline argument --comments.

I also tried the preserveComments found here but that just generates:

[13:37:42] GulpUglifyError: unable to minify JavaScript
Caused by: DefaultsError: `preserveComments` is not a supported option

Is there a way to achieve what the commandline argument suggests via the gulp-uglify plugin? If not possible, can i use the webpack plugin?

There is this workaround by specifying a regexp but i want to use the functionality directly from UglifyJS if possible. Besides, it doesnt keep the license headers like that either.


Solution

  • I had the same problem. I noticed the UglifyJS comments documentation suggested

    You can pass --comments all to keep all the comments, or a valid JavaScript regexp to keep only comments that match this regexp. For example --comments /^!/ will keep comments like /*! Copyright Notice */.

    So I tried "comments: /^!/":

    .pipe(uglify({
        mangle: true,
        output: {
            beautify: true,
            comments: /^!/
        }
    }))
    

    I now see the copyright comments in the resulting uglified code.