简体   繁体   English

Vue和Webpack:全球开发和生产变量

[英]Vue & Webpack: Global development and production variables

I'm using vue-cli to build my web app. 我正在使用vue-cli构建我的Web应用程序。 My app uses an api in a number of places like so: 我的应用程序在许多地方都使用了api,如下所示:

axios.post(API + '/sign-up', data).then(res => {
  // do stuff
});

The API variable is a constant containing the beginning of the address, eg, https://example.com . API变量是一个包含地址开头的常量,例如https://example.com

How would I detect whether this is a dev or prod build and set that variable accordingly? 我将如何检测这是dev还是prod版本,并相应地设置该变量? For now, I have a script tag in my index.html document and I am manually changing it for dev and prod: 现在,我在index.html文档中有一个脚本标签,并且正在为dev和prod手动更改它:

<script>var API = 'https://example.com'</script>

Is there a better way to handle this? 有没有更好的方法来解决这个问题?

If you're using the vue-cli webpack template, within the config folder you'll see two files: dev.env.js and prod.env.js. 如果您使用的是vue-cli Webpack模板,则在config文件夹中,您将看到两个文件:dev.env.js和prod.env.js。

Both files contain an object that is globally available throughout your Vue app: 这两个文件都包含一个在整个Vue应用程序中全局可用的对象:

dev.env.js dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})

prod.env.js prod.env.js

module.exports = {
  NODE_ENV: '"production"'
}

Note that string values require the nested single and double quotes. 请注意,字符串值需要嵌套的单引号和双引号。 You can add your own variables like so: 您可以像这样添加自己的变量:

dev.env.js dev.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API: '"http://localhost:8000"'
})

prod.env.js prod.env.js

module.exports = {
  NODE_ENV: '"production"',
  API: '"https://api.example.com"'
}

Now the variable can be accessed within any Vue method from the process.env object: 现在,可以从process.env对象的任何Vue方法中访问该变量:

process.env.API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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