Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally load a Nuxt.js plugin?

Tags:

nuxt.js

I have a custom plugin that should only run on production so I need to only load it when in that environment. Is there a way in nuxt.config.js to do that?

like image 326
Darrell Brogdon Avatar asked Dec 06 '25 08:12

Darrell Brogdon


2 Answers

The solution with build.extend no longer works for me.

Here is what I've come up with...

in nuxt.config.js:

plugins: [
  { src: '~/plugins/my-plugin-1.js' },
  { src: '~/plugins/my-plugin-2.client.js' },

  // Add plugins that should only run in production.
  ...(process.env.NODE_ENV === 'production' ? [
    { src: '~/plugins/my-production-plugin-1.client.js' }
  ] : []),
],
like image 129
Alexander Benjamin Avatar answered Dec 09 '25 01:12

Alexander Benjamin


It looks like the solution is in the build configuration of nuxt.config.js:

module.exports = {
    ...
    build: {
        extend (config, { isDev, isClient }) {
            if (!isDev && isClient) {
                config.plugins.push({src: '@/plugins/myPlugin', ssr: false})
            }
        }
    }
    ...
}
like image 21
Darrell Brogdon Avatar answered Dec 09 '25 01:12

Darrell Brogdon