Search code examples
vue.jswebpackbuildvue-cli-3terser

Vue CLI 3 remove console.log and code comments with Terser


I'm using VUE CLI 3 and I need to remove the console.log and code comments from the production built. This is my Terser setup:

webpack.config.js in src folder

    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,
        },
      }),
    ],
  },
};

My production workflow: Run npm run build -> cd dist -> npm run serve

The production build still outputs all console.log statements and shows code comments (<!-- -->). What do I need to change to remove them?


Solution

  • First of all: make sure you are configuring Terser correctly:

    terserOptions: {
        ecma: 6,
        compress: { drop_console: true },
        output: { comments: false, beautify: false }
    }
    

    npm run serve

    is usually a shortcut for:

    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
    

    So when your workflow is the above mentioned npm run build -> cd dist -> npm run serve then you are actually starting the dev server, which does not apply Terser.

    In order to run the production build you can use any webserver capable of serving static content:

    NodeJs examples:

    npm install -g serve
    serve -s dist
    

    or

    npm install -g node-static
    static dist