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,
...
}
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
})
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 is not defined
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.
UPDATE for Vue CLI 3
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
But an even better solution would be to configure a dev server.
Previous solution
Solution was quite simple:
Define a special variable for that case within webpack.dev.conf.js
plugins, omit using process.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}`)
}),
In \src\main.js
define it like this:
if (typeof baseURL !== 'undefined')
{
Vue.axios.defaults.baseURL = baseURL;
}
The answer above helped me. But I want to make an amendment. In /src/main.js
need define constant.
Example:
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}
Also don't need to add code in file webpack.dev.conf.js
. Although maybe this is only suitable for my problem.
My problem: Dynamic host in axios
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With