Home / Tutorials / Splitting Nuxt Js Configuration Based on the Environment
Splitting Nuxt Js Configuration Based on the Environment cover

Splitting Nuxt Js Configuration Based on the Environment

Learn how to split Nuxt Js configuration based on the environment of the project

6 mins

782

3 years ago

0 comments

Average

In this short post, you'll learn how to split Nuxt Js configuration based on the environment the project is running on. What that means is that the configuration will ensure that a specific code only runs on either development or production. Do note that by default the configuration that is defined will run on both environments.

Production Only Configuration


For example, imagine we plan to have Google Analytics on a Nuxt project and we want it to only run when the project is in a production environment. To do that we need to define the condition and below are the example to do so. 
if (process.env.NODE_ENV === "production") {
  config.modules.push(...[
    '@nuxtjs/google-adsense'
  ])

  config['google-adsense'] = {
    id: 'ca-pub-xxx'
  }
}
But before that do ensure to change the configuration (config.nuxt.js) as a variable and then export it on the last line of the file.
const config = {
  // config
}

export default config

Development Only Configuration


The same goes for development only Nuxt project, do define the condition so that it's only loaded on this environment. In the code below, it's to load custom axios on Nuxt Js to Configure Nuxt project to run HTTPS locally.
if (process.env.NODE_ENV === "development") {
  config.plugins = [...config.plugins, '~/plugins/axios']

  config.server = {
    https: {
      key: fs.readFileSync(path.resolve(__dirname, 'key.pem')),
      cert: fs.readFileSync(path.resolve(__dirname, 'cert.pem'))
    }
  }
}

Defining the environment for the project to run


By default running yarn watch will set the NODE_ENV to "development" but you can override it by updating the scripts like the following. You can refer more on Nuxt Js documentation,
"scripts": {
  "watch": "NODE_ENV=production nuxt"
}
Hope this post is helpful and if you enjoy it do share it with others. Cheers and happy learning.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this