Remove Console logs from production buils

Hi,

I started building a Vue project using vue-cli

npm install -g vue-cli

Now I am in a stage where I need to deploy the code in production.
I have observed that npm run build doesn’t remove the console logs.

Could you please help me on how to remove the console.logs from production build.

Thanks
Praveen

1 Like

You will require babel plugin to remove the console.log from production build.
npm install babel-plugin-transform-remove-console --save-dev

If you are using vue-cli 3. you will find babel.config.js file where you can include this plugin.

const removeConsolePlugin = []
if(process.env.NODE_ENV === 'production') {
  removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
  presets: [
    '@vue/app'
  ],
  plugins: removeConsolePlugin
}
8 Likes

Hi Jayesh,

Thank you for your reply!

I am using an older version of Vue Cli and it uses webpack.

As I am not using babel, could you please help me on how to achieve this without babel.

Following is the config/index.js file

‘use strict’
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require(‘path’)

module.exports = {
dev: {

// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},

// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-


/**
 * Source Maps
 */

// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',

// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,

cssSourceMap: true

},

build: {
// Template for index.html or CustomerDetails.html
index: path.resolve(__dirname, ‘…/src/main/webapp/index.html’),

// Paths
assetsRoot: path.resolve(__dirname, '../target/webapp/dist'),
assetsSubDirectory: 'static',
assetsPublicPath: 'dist/',

/**
 * Source Maps
 */

productionSourceMap: false, //productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',

// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],

// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report

}
}

You can do without babel also, for earlier version of vue cli you will find webpack config for prod under build > webpack.prod.conf.js under plugins array for UglifyJsPlugin you need to add drop_console: true under compress option.

new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        drop_console: true
      },
      sourceMap: true
    })

If you are interested are other useful compress option you can use.

3 Likes

I am using node 10.7.0 so this cant work for me, cause babel need node >=4 9=<
Do you know about any other solution than babel? I was trying to configuje webpack somehow in vue.config.js but I can’t solve that

I use node v10,7.0 too, it’s work.

$ vue add @vue/babel

📦  Installing @vue/cli-plugin-babel...

yarn add v1.7.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.1.3: The platform "linux" is incompatible with this module.
info "fsevents@1.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
error upath@1.0.4: The engine "node" is incompatible with this module. Expected version ">=4 <=9".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
error Found incompatible module
 ERROR  command failed: yarn add -D @vue/cli-plugin-babel

Maybe you’re using Windows? Cause it doesn’t work for my Manjaro linux…

@keromudo you can use webpack uglifyjs plugin
Install npm i -D uglifyjs-webpack-plugin

In vue.config.js

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const isProd = process.env.NODE_ENV === "production"
module.exports = {
  configureWebpack: {
    optimization: {
      minimizer: isProd ? [
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_console: true
            },
          }
        })
      ] : []
    }
  }
}
2 Likes

That works! Thank you @Jayesh for advice… Vue CLI 3 is supposed to be easier to maintain but I kinda didn’t get the idea of vue.config.js … I am trying to get familiar with it :roll_eyes::joy:

Well, the idea is as follows:

  1. With the old webpack config, you could directly edit the webpack config, which as great for quick edits, but a nightmare when you wanted to update to a new version of the template.
  2. So we abstracted the base config away into an npm package. Which means “zero config” For the initial project and easy updates by simply updating the @vue/cli-service package
  3. But people still need a way to adjust the webpack config somehow - that’s where the chainWebpack and configureWebpack options in vue.config.js come into play.

So yeah, you have to once wrap your head around how to configure webpack through vue.config.js, but then it’s much easier to maintain in the longrun then the old template-based approach, especially for upgrades.

2 Likes

Thanks Jayesh.

This worked for me. I somehow had missed webpack config file.

Just curious why the -D flag is used… Isn’t this package only needed in production?
npm i -D uglifyjs-webpack-plugin

uglifyjs-webpack-plugin helper plugin is needed at the development time, meaning during webpack transpilation, not to be added as part of production build.

I’m not seeing this work on the latest vue cli:

error: Unexpected console statement (no-console) at src/router/index.js:284:5:
  282 |       })
  283 |   } else {
> 284 |     console.log("No role required. Letting user pass to: " + to.path)
      |     ^
  285 |     next()
  286 |   }
  287 | })

I’ve not changed any of my babel settings:

cat babel.config.js 
const removeConsolePlugin = []
if (process.env.NODE_ENV === "production") {
  removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"],
  plugins: removeConsolePlugin
}

Nevermind, needed to do:

https://cli.vuejs.org/migrating-from-v3/#vue-cli-plugin-babel-vue-babel-preset-app

After re-reading and following (array wasn’t right):

it’s .js files that aren’t getting processed. .vue are OK now.