問題記錄:在生產環境中不要出現@licnese,但是vue打包之后並不能把所有注釋都消除掉
刪除注釋要引入webpack的plugins : terser-webpack-plugin (UglifyJsPlugin已經被官方廢棄)
在命令終端 輸入下面的命令: 可以在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 }) },