有没有办法保留许可证注释?

Is there a way to preserve license comments?

我在 webpack.config.js 文件中使用 babel-loader,但我注意到它删除了以下形式的许可证注释:

/*! whatever **/

有没有办法保存它们? 我注意到 babel 有一个 comments 选项,但我想这会保留 any 评论,而不仅仅是许可证。

const webpack = require('webpack');

module.exports = {
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.js'
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: 'vue-style-loader!css-loader!sass-loader',
            js: 'babel-loader'
          }
        }
      },
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
        }
      }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: false,
      }
    })
  ],
};

我已经试过了:

plugins: [
    new webpack.optimize.UglifyJsPlugin({
      output:{
        comments: true
      }
})

以及 comments: '/^!/'comments: /^!/。 什么都不管用。

如果我从 webpack 配置中删除整个 plugins 选项,它只会保留注释。

我也试过使用许可证注释,例如:

/** comments */

/*! comments */

/*! @license comments */

/*! @preserve comments */

尝试添加 output 选项。

plugins : [
  new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false,
      drop_console: false
    },
    output: {
      comments: '/^!/'
    }
  })
]

我不确定它是否有效,因为我从未使用过它。 有关详细信息,请参阅 this

请告诉我它是否有效。

那是一个 bug,自 2015 年以来一直在 webpack/uglify,并且从未得到修复。

他们应该使用 this by rather adding extractComments to true but still it won't work for some people so a year later in 2019 another PR 修复它已经开放,据说可以修复它。

new UglifyJSPlugin({
  sourceMap: true,
  extractComments: true
})

所以这是一个已经存在多年的已知错误。也许黑客确实存在,但这是一般情况。

工作技巧:

const WrapperPlugin = require('wrapper-webpack-plugin');
let licenseComments = [];

module.exports = {
    ...
    optimization: {
        minimize: true,
        minimizer: [
            new UglifyJsPlugin({}),
            new WrapperPlugin({
                header: function () {
                    var unique = licenseComments.filter((v, i, a) => a.indexOf(v) === i); 
                    return unique.map(x => '/*' + x + '*/').join('\n');
                }
            })
        ],
    },
    module: {
        {
            test: /\.js$/,
            use: {
                loader: 'babel-loader',
                options: {
                    shouldPrintComment: (val) => {
                        if (/license/.test(val)) {
                            licenseComments.push(val);
                        }
                        return false;
                    },
                }
            }
        }
    ...