简体   繁体   中英

Vue.js: Defining computed environment variables in vue.config.js (vue cli 3)

The documentation for Vue CLI 3 says here https://cli.vuejs.org/guide/mode-and-env.html#using-env-variables-in-client-side-code :

You can have computed env vars in your vue.config.js file. They still need to be prefixed with VUE_APP_ . This is useful for version info process.env.VUE_APP_VERSION = require('./package.json').version

This is exactly what I want to do. But I couldn't find out how to actually define the env var there in vue.config.js . I tried:

module.exports = {
    process.env.VUE_APP_VERSION: require("../package.json").version,
    ...
}

But it just produces an error:

ERROR  SyntaxError: Unexpected token .
    /Users/lhermann/htdocs/langify/frontend/vue.config.js:2
    process.env.VUE_APP_VERSION: require("../package.json").version,
           ^

Does anyone know?

The environment variables are not part of the config export, you just set them in the vue.config.js file, eg

process.env.VUE_APP_VERSION = require('./package.json').version

module.exports = {
  // other config, eg configureWebpack
}

I've raised a feature-request to get an example added to the docs ~ https://github.com/vuejs/vue-cli/issues/2864

Common Environment Variables:

According to Environment Variables and Modes documentation , you can specify env variables by placing .env files in your project root.

The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.

.env                # loaded in all cases
.env.local          # loaded in all cases, ignored by git
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode, ignored by git

Your .env file(s) should look like this:

VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value

Note that only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin .

Computed Environment Variables:

If you want variables that need pre-processing, you can use chainWebpack property of vue.config.js to inject anything you want:

// vue.config.js

module.exports = {
  // ...,
  chainWebpack: config => {
    config.plugin('define').tap(args => {
      args[0]['process.env'].APP_VERSION = `"${require("../package.json").version}"`
      return args
    })
  }
  // ...
}

Using this method, you can inject anything, with any names you want; you are not bound by the VUE_APP_ limitation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM