Search code examples
vue.jsvuexobfuscationminify

Vue CLI minifies for production, but how can properties and other definitions also be shortened?


I looked at an output file (e.g. app.4a7888d9.js) that the Vue CLI generated to see what actually got reduced and I saw that properties declared in the 'data' object, methods declared in the methods object, etc. retain their original name. Same with Vuex state properties.

I'm not trying to obfuscate my code entirely but I do use rather long descriptive names which could benefit of minification. Please don't hate, but an example of a worst case scenario of a property name I have is scheduledTransactionConditionActiveComponent

Is there a better way to achieve minification besides what the cli does by default ? If I should use a different package for this, is there one that's proven for vue?


Solution

  • Vue CLI uses terser-webpack-plugin for minification, and property mangling is disabled by default. You could enable it in your Vue config as follows:

    // vue.config.js
    module.exports = {
      chainWebpack: config => {
        config.optimization.minimizer('terser').tap(args => {
          const opts = args[0]
    
          opts.terserOptions.mangle = {
            ...opts.terserOptions.mangle,
            properties: true, // mangle all property names
          }
    
          return args
        })
      }
    }
    

    The Terser docs also recommend selective property mangling (e.g., by only applying it to names that match a regexp). For example, you could configure Terser to only mangle properties that end with an underscore:

    // vue.config.js
    module.exports = {
      chainWebpack: config => {
        config.optimization.minimizer('terser').tap(args => {
          const opts = args[0]
    
          opts.terserOptions.mangle = {
            ...opts.terserOptions.mangle,
            properties: {
              regex: /_$/, // mangle property names that end with "_"
            },
          }
    
          return args
        })
      }
    }
    

    Note: Although this works well for data props, this mangling does not work for component names (i.e., property names under components).