vuejs configuration: using a global variable?
Import it.
<script> import config from "../config" module.exports = { data: function() { return { obj: null } }, created: function() { this.$http.get(config.API_LOCATION + '/call').then(res => { // Do some business }, res => { // Handle some error }); } }</script>
Or just the location.
<script> import { API_LOCATION } from "../config" module.exports = { data: function() { return { obj: null } }, created: function() { this.$http.get(API_LOCATION + '/call').then(res => { // Do some business }, res => { // Handle some error }); } }</script>
PROD: config/prod.env.js
append your VAR='"value"'
'use strict'module.exports = { NODE_ENV: '"production"', API_LOCATION: '"https://production URL"'}
DEV: config/dev.env.js
append your VAR='"value"'
'use strict'const merge = require('webpack-merge')const prodEnv = require('./prod.env')module.exports = merge(prodEnv, { NODE_ENV: '"development"', API_LOCATION: '"http://localhost"'})
Your variable will available in process.env.API_LOCATION
or process.env.VAR_NAME
TL;DR; Global configuration in Vue is done using the .env
and .env.production
files that you create in the route folder of the app (next to package.json)
I can confirm that in Vue using the Vue CLI .env
file gets loaded automatically when you run npm run serve
But keep in mind the following that I checked:
Variables in the
.env
files have to start withVUE_APP
prefix to be automatically picked up and available asprocess.env.VUE_APP_MYVAR
in the codeIf you're defining JS objects such as 'VUE_APP_MY_OBJECT={a:100}
then you'll have to parse it to JSON before using it in the code
JSON.parse(process.env.VUE_APP_MY_OBJECT)`If you're not using Webpack you might have to fiddle a bit with it to pick these config files up. According to this answer it looks like webpack should do it automatically. Dunno