Vue CLI 3 使用 Terser 删除 console.log 和代码注释

Tom*_*Tom 5 build webpack vue.js vue-cli-3 terser

我正在使用 VUE CLI 3,我需要从构建的产品中删除console.log代码注释。这是我的Terser设置:

webpack.config.jsSRC文件夹

    module.exports = {
mode: 'production',
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          ecma: undefined,
          warnings: false,
          parse: {},
          compress: {drop_debugger},
          mangle: true, // Note `mangle.properties` is `false` by default.
          module: false,
          output: null,
          toplevel: false,
          nameCache: null,
          ie8: false,
          keep_classnames: undefined,
          keep_fnames: false,
          safari10: false,
        },
      }),
    ],
  },
};
Run Code Online (Sandbox Code Playgroud)

我的生产工作流程:运行npm run build-> cd dist->npm run serve

生产版本仍会输出所有console.log语句并显示代码注释(<!-- -->)。我需要更改什么才能删除它们?

mad*_*low 8

首先:确保您正确配置了Terser

terserOptions: {
    ecma: 6,
    compress: { drop_console: true },
    output: { comments: false, beautify: false }
}
Run Code Online (Sandbox Code Playgroud)

npm run serve

通常是一个快捷方式:

vue-cli-service

vue-cli-service --help

  Usage: vue-cli-service <command> [options]

  Commands:

    serve     start development server
    build     build for production
    inspect   inspect internal webpack config
    lint      lint and fix source files
Run Code Online (Sandbox Code Playgroud)

因此,当您的工作流程如上所述时,您npm run build -> cd dist -> npm run serve实际上是在启动不应用 Terser 的开发服务器。

为了运行生产版本,您可以使用任何能够提供静态内容的网络服务器

NodeJs 示例:

npm install -g serve
serve -s dist
Run Code Online (Sandbox Code Playgroud)

或者

npm install -g node-static
static dist
Run Code Online (Sandbox Code Playgroud)