5

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

/*! whatever **/

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

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: /^!/。没有任何效果。

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

我还尝试使用许可注释,例如:

/** comments */

/*! comments */

/*! @license comments */

/*! @preserve comments */
4

3 回答 3

3

这是一个错误,自 2015 年以来一直存在于 webpack/uglify 中,并且从未得到修复。

他们应该通过添加来修复它extractComments它仍然对某些人true不起作用,所以一年后的 2019 年,另一个 PR已经开放,据说可以修复它。

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

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

于 2020-03-11T12:39:28.350 回答
0

工作技巧:

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;
                    },
                }
            }
        }
    ...
于 2020-03-11T15:14:37.057 回答
-1

尝试一次添加output选项。

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

我不确定它是否会起作用,因为我从未使用过它。有关更多详细信息,请参阅

请让我知道它是否有效。

于 2018-01-24T07:06:39.097 回答