Posts Learn Components Snippets Categories Tags Tools About
/

Splitting Nuxt Js Configuration Based on the Environment

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

3 years ago

6 mins read

761 views

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.

Alternative Tags

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

new

PostSrc Code Snippets

Learn new snippets today, level up your Laravel, Alpine JS, Vue JS, Tailwind CSS skills and more.

Learn New Snippets

Sponsors 👑

+ Add Yours
new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components
)