7

I am trying to figure out how to deploy my vue app that was generated with vue-cli 3 to production. I plan on hosting it as static files (that is no server side code). I need to set certain variables in my code based on the current environment (dev vs production). These include api-urls and authentication information (none of which is secret).

What is the best way of doing this?

Here are the config docs for vue-cli 3: https://cli.vuejs.org/config/

2
  • Please share your webpack configuration. If you don't have one, you'll need one in order to use the DefinePlugin. (webpack.js.org/plugins/define-plugin) Commented Aug 9, 2018 at 10:36
  • The webpack config is hidden since I am using vue-cli but it can be configured using vue.config.js - file. The possible options for this file is listed in the link included. Commented Aug 9, 2018 at 11:16

3 Answers 3

14

You can just add your variables to existing DefinePlugin config with chainWebpack:

// vue.config.js

module.exports = {
  chainWebpack: config => {
    config
      .plugin('define')
      .tap(args => {
          args[0] = {
             ...args[0],
             "MY_API_URL": JSON.stringify(process.env.URL),
             // other stuff
          }
          return args
       })
  }
}

And configure environment variables in .env.

Sign up to request clarification or add additional context in comments.

Comments

5

You have to start the variable names with VUE_APP (https://cli.vuejs.org/guide/mode-and-env.html)

Comments

4

To make the config values part of process.env a slight update to Max Sinev's answer would be

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugin("define").tap(args => {
      let _base = args[0]["process.env"];
      args[0]["process.env"] = {
        ..._base,
        "API_URL": JSON.stringify(process.env.URL),
      };
      return args;
    });
  }
}

Now API_URL can be accessed as precess.env.API_URL

1 Comment

As I tried, now API_URL seems can be accesed as API_URL

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.