I can't find a way to access environment variables (especially within a component). I created a brand new project with:
vue init nuxt/starter new-project
cd new-project
npm install
npm run dev
nuxt.config.js
module.exports = {
...
env: {
hey: 'hey'
}
}
pages/index.vue
<script>
import Logo from '~/components/Logo.vue'
export default {
components: {
Logo
},
mounted () {
console.log(process.env)
}
}
</script>
console.log()
prints an empty object. I read in the documentation that you could access environment variables with process.env
. What am I doing wrong? :)
I am using the latest version of nuxt.js ([email protected]
) and my version of node is 8.2.1
.
Hello @LeCoupa, maybe I can help you.
On my nuxt.config.js I added this line:
env: {
baseUrl: process.env.BASE_URL,
}
Inside my component footer.vue I access this info like that:
<template>
<footer>
Visit our website for more documentation : <a href="https://nuxtjs.org" target="_blank">nuxtjs.org</a>
ENV: {{ env }}
</footer>
</template>
<script>
export default {
components: {
},
data() {
return {
env: process.env.baseUrl,
};
},
mounted() {
},
};
</script>
I hope this snippet help you
@gtso86 I have just tested your snippet on a brand new nuxt project and I still get an empty object printed. :/
Here is my nuxt.config.js file:
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'nuxt-env',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
env: {
baseUrl: process.env.BASE_URL
},
build: {
/*
** Run ESLINT on save
*/
extend (config, ctx) {
if (ctx.dev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
OH, maybe is because I not used a good variable!
TRY set another example inside env object like you used before and se if works:
env: {
hey: 'hey',
}
Base_URL isn't a default variable inside env object. In my case I'm using Express template and changing this inside server/index.js
const app = express();
const host = process.env.HOST || '127.0.0.1';
const port = process.env.PORT = 5000; // eslint-disable-line no-multi-assign
process.env.BASE_URL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT}`; // eslint-disable-line no-multi-assign
But before I was testing the same template as you (Nuxt starter template)... In that case, I created a extra file called server.js
and add this lines there:
// Env configs
const host = process.env.HOST || '127.0.0.1';
const port = process.env.PORT = 4000;
const uri = 'http://localhost:' + port;
process.env.BASE_URL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT}`; // eslint-disable-line no-multi-assign
_The last line is I manually creating the BASE_URL var..._
I also changed how to build the server changing package.json
. I got these example here: https://nuxtjs.org/api/configuration-dev/#the-dev-property
.json
"scripts": {
"dev": "node server.js",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node .build/server.js",
"generate": "nuxt generate",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
"precommit": "npm run lint"
},
BTW I strongly suggest you read all FAQ section. I used a lot of inspiration from there to start build my first Nuxt app.
@LeCoupa
In Nuxt 1.0.0-alpha.4 up through 1.0.0-rc4, env variables are working for me in all my Vue components. They are part of my current project and working fine.
I can reproduce what you're describing, but there doesn't seem to be a real issue.
This might be more related to Node
, and not necessarily related to Nuxt
.
console.log(process.env)
will log out an empty object when I add environment vars like this:
// nuxt.config.js
module.exports = {
env: {
hello: 'world'
}
}
// SomeVueComponent.vue
export default = {
mounted () {
console.log(process.env) // {}
}
}
If I log out the actual env variable, I get what I am expecting:
// SomeVueComponent.vue
export default = {
mounted () {
console.log(process.env.hello) // world
}
}
Environement variables works perfectly, it's just that Webpack replace in your code everytime you are using process.env.X
by your environement variable value. But you cannot list all your variable with process.env
.
Thanks to all comments to help clarifying this issue :)
@Atinux I don't get this last part... webpack does what?
@Atinux would it be a bad practice to assign env variables to Vue.prototype in a plugin ?
because process.env.xxx is not interpreted inside "template" element from vue single-component files.
like this :
import Vue from 'vue'
/**
* App logic that not belongs to any specific component
*/
export default (context) => {
// access drupalBaseUrl from our templates
Vue.prototype.$drupalBaseUrl = process.env.drupalBaseUrl
}
then in templates :
<template>
<div>
<img v-if="post.image" :src="$drupalBaseUrl + '/' + post.image" />
</div>
</template>
@nyl-auster For what it's worth, I don't think it's a good practice, but I wouldn't knock you for using it. I'd rather go with some sort of service import, I think it's best to try and utilize some sort of dependency injection system rather than rely on globals.
If you haven't already considered it, maybe you could put that in a $cms
prop instead. That way if you have more configuration options that you want available you could add them to the same prop instead of polluting the Vue prototype.
Have this:
<h1>{ $cms.siteName }</h1>
<img v-if="post.image" :src="$cms.baseUrl + '/' + post.image" />
<!-- Maybe use $cms so if you switch away from Drupal, you already have this abstracted ;) -->
instead of this:
<h1>{ $drupalSiteName }</h1>
<img v-if="post.image" :src="$drupalBaseUrl + '/' + post.image" />
I would do this with a Vue mixin.
1: Create the mixin
// assets/js/mixins/siteConfig.js
export default {
data () {
siteName: process.env.SITENAME,
baseUrl: process.env.DRUPALBASEURL,
theme: process.env.THEME
}
}
2: Create an alias for easier imports:
// nuxt.config.js
module.exports = {
extend (config) {
config.resolve.alias['Mixins'] = '~/assets/js/mixins'
}
}
3: Import the mixin into any component you need
<!-- components/post.vue -->
<template>
<div>
<h1 :class="theme">{ siteName }</h1>
<img v-if="post.image" :src=`${baseUrl}/${post.image}/`>
</div>
</template>
<script>
import siteConfig from 'Mixins/siteConfig'
export default {
mixins: [ siteConfig ]
}
</script>
@jsonberry, nice example! thank you man.
@LeCoupa, you can use mixins with methods and data globally too .
Global mixins will be available in all life cycle of vue and nuxt like pages, templates, fetch, async, middleware and others.
plugins/mixins.js
import Vue from 'vue'
Vue.mixin({
methods:{
// Available in all lyfe cycle of vue and nuxt.
mg_login(payload){
this.$store.dispatch('loginService/signin', payload)
.then(() => this.$router.replace({ path: '/' }))
},
mg_logout(payload){
console.log('hello')
this.$store.dispatch('loginService/signin')
}
}
})
nuxtconfig.js
plugins:['~/plugins/mixins'],
login.vue
<button type="button" class="btn btn-primary" @click="mg_login(model)"> Login </button>
logout.vue
<button type="button" class="btn btn-primary" @click="mg_logout()"> Logout </button>
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
@nyl-auster For what it's worth, I don't think it's a good practice, but I wouldn't knock you for using it. I'd rather go with some sort of service import, I think it's best to try and utilize some sort of dependency injection system rather than rely on globals.
If you haven't already considered it, maybe you could put that in a
$cms
prop instead. That way if you have more configuration options that you want available you could add them to the same prop instead of polluting the Vue prototype.Have this:
instead of this:
I would do this with a Vue mixin.
1: Create the mixin
2: Create an alias for easier imports:
3: Import the mixin into any component you need