问题描述
我正在使用安装了 VueAxios 的标准 Vue starer webpack 模板.我想在使用 dev
命令构建时使用 .env 变量配置 axios.我在 /config/index.js
中设置了所有内容:
I am using a standard Vue starer webpack template with VueAxios installed. I want to configure axios using .env variable when building with dev
command. I have everything set up within /config/index.js
:
const devEnv = require('./dev.env')
module.exports = {
...
host: devEnv.host || 'localhost',
port: devEnv.port || 8080,
...
}
然后我在同一目录中的 dev.env.js
中定义我的主机和端口,一切正常.
Then I define my host and port in dev.env.js
in the same directory and it all works fine.
const dotenv = require('dotenv').config({path: '../.env'})
let host = process.env.VUE_HOST;
let port = +process.env.VUE_PORT;
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
host,
port
})
但问题是我无法在我的 Vue 应用程序的 src/main.js
中访问主机值.
But the problem is that I can't access host value within src/main.js
of my Vue app.
如果我尝试这样做,我会收到一个错误
If I try to do it like this I get an error that
vue 未定义
import axios from 'axios'
import VueAxios from 'vue-axios'
...
Vue.use(VueAxios, axios)
Vue.axios.defaults.baseURL = `http://${process.env.host}:${process.env.port}`;
虽然端口工作正常,但主机没有并抛出错误.
Though the port works fine, the host does not and throws an error.
推荐答案
Vue CLI 3 的更新
您现在需要做的只是在您的 .env
文件中设置 VUE_APP_BASE_URL
.然后你就可以像这样访问它:
All you need to do now is just set VUE_APP_BASE_URL
in your .env
file. Then you'll be able to access it like this:
process.env.VUE_APP_BASE_URL
但更好的解决方案是配置开发服务器.
以前的解决方案
解决方案很简单:
在
webpack.dev.conf.js
插件中为这种情况定义一个特殊变量,为此省略使用process.env
.
Define a special variable for that case within
webpack.dev.conf.js
plugins, omit usingprocess.env
for that.
new webpack.DefinePlugin({
'process.env': require('../config/dev.env'), // You can't use this for baseURL
'baseURL': JSON.stringify(`http://${HOST || config.dev.host}:${PORT || config.dev.port}`)
}),
在 srcmain.js
中这样定义:
if (typeof baseURL !== 'undefined')
{
Vue.axios.defaults.baseURL = baseURL;
}
这篇关于在 VueAxios 中从 .env 设置 baseURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!