1. 程式人生 > 實用技巧 >vue-打包遇到的問題

vue-打包遇到的問題

vue-打包

打包後用iframe引入的html檔案亂碼

原因:
解決:用live server開啟就不會亂碼

生產環境移除所有的console命令

三種解決方法

發現vue-cli3.0在打包過程中就使用了terser-webpack-plugin外掛進行優化,具體配置可以node_modules/@vue/cli-service/lib/config/prod.js中看到。
if (process.env.VUE_CLI_TEST) {
  webpackConfig.optimization.minimize(false)
} else {
  const TerserPlugin = require('terser-webpack-plugin')
  const terserOptions = require('./terserOptions')
  webpackConfig.optimization.minimizer([
    new TerserPlugin(terserOptions(options))
  ])
}
這裡使用了環境變數進行控制,只有打生產包的時候才會呼叫這個外掛進行打包優化。

terser-webpack-plugin的具體配置在同一個資料夾下terserOptions.js中,只要在這個檔案中compress物件加入以下程式碼:
warnings: false,
drop_console: true,
drop_debugger: true,
pure_funcs: ['console.log'],
安裝外掛
npm install terser-webpack-plugin --save-dev
module.export = {
  configureWebpack: (config)=>{
    if(process.env.NODE_ENV === 'production'){
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
    }
  }
}
npm install babel-plugin-transform-remove-console --save-dev
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
let plugins = [
  [
    "import",
    {
      libraryName: "ant-design-vue",
      libraryDirectory: "es",
      style: true
    }
  ]
];
if (IS_PROD) {
  plugins.push("transform-remove-console");
}
 
module.exports = {
  presets: ["@vue/app"],
  plugins
};