Reputation: 2955
I'm using Nuxt JS 2.4.5 and am building a static website in SPA mode where running npm run build && npm run generate
will generate my website in a dist/
directory.
I'm trying to figure out how I can do an if () {} else {}
statement within either mounted()
or created()
to check whether I'm running my project in dev mode or production/generated website mode so that I can include a Google Analytics snippet, or conditionally render other content on the page based on the mode.
I've taken a look through the documentation and have found the following: https://nuxtjs.org/api/configuration-dev which looks to be of some help to me, but haven't yet put this into practice as I'm unsure of the best approach and am looking for guidance or an example.
I'm potentially thinking about trying the following:
layouts/default.vue
...
mounted () {
if (process.env.NODE_ENV == 'production') {
// run code on generated static site, e.g: Google Analytics
} else {
// run code if in dev mode, e.g: http://localhost:3000/
}
}
...
...and then in my package.json
file I'd need to set production mode potentially on the generate command which builds the website using: NODE_ENV=production
package.json
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "NODE_ENV=production nuxt generate"
}
If I then run npm run build && npm run generate
it should then build my static website and the Google Analytics code should then work.
I'l love to find out how other people are doing this and their solutions, I'm trying to get Google Analytics to work for every page and thus the layouts directory seems a good place to put the code.
Upvotes: 0
Views: 266
Reputation: 81
I would set this up in the created()
or beforeCreate()
hook in the default.vue
. There's no hard and fast rules against setting it up like this.
If you were doing this not using Nuxt but instead vanilla Vue, I'd put it in the main.js
file where Vue is initialized.
Upvotes: 1