vue2打包后删除注释---遇坑记录

问题记录:在生产环境中不要出现@licnese,但是vue打包之后并不能把所有注释都消除掉

删除注释要引入webpack的plugins : terser-webpack-plugin   (UglifyJsPlugin已经被官方废弃)

相关 terser-webpack-plugin文档

在命令终端 输入下面的命令: 可以在output.js中查看到vue的webpack配置

vue inspect --mode=production > output.js

可以看到vue的webpack配置如下(optimization:{minimizer}) terser-webpack-plugin主要修改的是optimization.options.terserOptions下的配置

optimization: {
    minimizer: [
      {
        options: {
          test: /.m?js(?.*)?$/i,
          chunkFilter: () => true,
          warningsFilter: () => true,
          extractComments: false,
          sourceMap: false,
          cache: true,
          cacheKeys: defaultCacheKeys => defaultCacheKeys,
          parallel: true,
          include: undefined,
          exclude: undefined,
          minify: undefined,
          terserOptions: {
       //可以看到vue的原始设置是对@license进行保留的,所以目的就是把所有license注释掉,把comments设置为false即可 output: { comments: /^**!|@preserve|@license|@cc_on/i }, compress: { arrows: false, collapse_vars: false, comparisons: false, computed_props: false, hoist_funs: false, hoist_props: false, hoist_vars: false, inline: false, loops: false, negate_iife: false, properties: false, reduce_funcs: false, reduce_vars: false, switches: false, toplevel: false, typeofs: false, booleans: true, if_return: true, sequences: true, unused: true, conditionals: true, dead_code: true, evaluate: true }, mangle: { safari10: true } } } } ] },

接下来就是遇坑记录了,先后在网上尝试了多种方法,最后才试成功

chainWebpack: config => {
        // 删除注释
        // 错误方法1,这种方法会报错,原因不明,估计是vue不允许用这样的方式改原有的webpack配置代码
        if (process.env.NODE_ENV === 'production') {
            config.optimization.minimizer[0].options.terserOptions.output.comments = false
        }
        //错误方法2 ,这个方法是在该plugins插件的github上找到的方法,最终查看output.js时发现是在 config.optimization.minimizer数组中在新增了一个对象,这个对象并不能覆盖掉原先vue的webpack配置
        config.optimization.minimize = true
        config.optimization.minimizer().use(TerserPlugin, [{
            extractComments: false,
            terserOptions: {
                format: {
                    comments: false,
                },
                compress: {
                    drop_console: true,
                    drop_debugger: true,
                    pure_funcs: ['console.log']
                }
            }
        }])
    },    

正确方法:这种做法只会在原先的config.optimization.minimizer上修改配置,不会新增对象,所以最终打包后就没有@licnese这种配置了

chainWebpack: config => {
        // 删除注释
        config.optimization.minimizer('terser').tap((args) => {
            args[0].terserOptions.compress.drop_console = true
            args[0].terserOptions.compress.drop_debugger = true
            args[0].terserOptions.compress.pure_funcs = ['console.log']
            args[0].terserOptions.output = {
                comments: false
            };
            return args
        })
    },
原文地址:https://www.cnblogs.com/gengzhen/p/15251600.html