下面是详细的讲解。
什么是环境变量和模式
在开发中,我们需要根据不同的环境和需求来进行不同的配置,比如在开发环境和测试环境中使用不同的 apiUrl,或者在不同的模式下加载不同的配置文件。
vue-cli3.0 提供了非常便捷的配置方法来实现这些需求,分别是环境变量和模式。
环境变量:
在 vue-cli3.0 中,环境变量默认有三个:development、production 和 test。我们可以在不同的环境中设置不同的变量,然后在代码中引用。
模式:
模式可以理解为不同的构建版本,我们可以通过 mode 属性来指定模式,在不同的模式中可以设置不同的配置。
环境变量的配置方法
- 在项目根目录创建 .env 文件,配置环境变量。如:
VUE_APP_API_URL=http://localhost:3000
- 在代码中引用该变量,可以使用 process.env.VUE_APP_API_URL 来获取。
示例:
在 vue.config.js 中进行配置,在 dev 环境的情况下设置 apiUrl 为 http://localhost:3000:
module.exports = {
devServer: {
proxy: {
'/api': {
target: process.env.VUE_APP_API_URL,
pathRewrite: {
'^/api': ''
}
}
}
}
}
在代码中使用
axios.get('/api/getData').then(res => {
console.log(res.data)
})
模式的配置方法
- 在 package.json 中设置模式
"build": "vue-cli-service build --mode production"
- 在项目根目录下,创建不同模式的配置文件 vue.config.modeName.js,如 vue.config.production.js,进行不同配置。
// vue.config.production.js
module.exports = {
apiUrl: 'http://api.prod.com'
}
// vue.config.development.js
module.exports = {
apiUrl: 'http://api.dev.com'
}
- 在代码中使用该变量,使用 vue-cli-service 的 mode 参数来指定当前使用的模式,如:
console.log(process.env.apiUrl)
示例:
在 axios 中设置不同模式下的 baseUrl:
// vue.config.production.js
module.exports = {
baseUrl: 'http://prod.com'
}
// vue.config.development.js
module.exports = {
baseUrl: 'http://dev.com'
}
在 axios 中使用
const apiUrl = process.env.NODE_ENV === 'production' ? process.env.baseUrl : ''
axios.get(`${apiUrl}/api/getData`).then(res => {
console.log(res.data)
})
以上就是关于“vue-cli3.0 环境变量与模式配置方法”的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:vue-cli3.0 环境变量与模式配置方法 - Python技术站