Vue.js: Is it possible to do "Conditional compilation" with a Vue project?

In for example Swift/iOS development, it's possible to differentiate builds for different environments with "flags" such as:

#if STAGING
  // one set of logic here
#endif

#if PRODUCTION
  // another set of logic here
#endif

Is it possible to achieve the same with a Vue.js project, and how would we go about doing it? I am aware of makes different routes conditionally available for different roles (which is also quite neat), but I am optimally looking for the option to differentiate on a source code level.

Hope someone has some great insights! It could include:

Upvotes: 3

Views: 1546

Answers (2)

lijun liang
lijun liang

Reputation: 1

just change the vue-loader output.

the source code

    <template v-if="process.env.NODE_ENV === 'development'">
      development only
    </template>

default output

var render = function() {
  var _vm = this
  var _h = _vm.$createElement
  var _c = _vm._self._c || _h
  return _c(
    "div",
    { attrs: { id: "app" } },
    [
      _vm.process.env.NODE_ENV === "development"
        ? [_vm._v(" development only ")]
        : _vm._e(),
      _c("router-view")
    ],
    2
  )
}

just use regex to replace _vm.process.env. by process.env is ok.

// webpack.config.js
    module: {
      rules: [{
        // must set post
        enforce: 'post',
        test: /\.vue$/,
        use: [{
          loader: './myLoader'
        }]
      }]
    }


// myLoader.js
module.exports = function (source, map) {
  if (source.indexOf('_vm.process.env') > -1) {
    source = source.replace(/_vm.process.env/g, 'process.env')
  }
  this.callback(
    null,
    source,
    map
  )
}

Final the vue-loader result change

var render = function() {
  var _vm = this
  var _h = _vm.$createElement
  var _c = _vm._self._c || _h
  return _c(
    "div",
    { attrs: { id: "app" } },
    [
      // change to true
       true
        ? [_vm._v(" development only ")]
        : undefined,
      _c("router-view")
    ],
    2
  )
}

Upvotes: 0

Cosimo Chellini
Cosimo Chellini

Reputation: 1730

you have the ability to use this syntax

 if(process.env.NODE_ENV === 'production') {
        console.log("this is the prod env!!!!!!!!!!");
        config.output.path = path.resolve(__dirname, "dist");
    }

make sure that when you run the script with the correct env's for each environment (local, dev, staging, prod etc ..) :D

Upvotes: 1

Related Questions