How to Dynamically Import SCSS Stylesheets in Nuxt using an Environment Variable

Viewed 1010

We are running Nuxt in a monorepo and things are working well. We are utilizing a /base directory containing our reusable components and stylesheets, and each project has its own subdirectory within a /projects directory.

Our global variables/mixins are being added to the base nuxt.config.js via the @nuxtjs/style-resources module which we then extend and import into the project's own nuxt.config.js.

In our components, we are hoping to dynamically import a project-specific stylesheet using an environment variable. We currently have something like:

//component-name.vue

<template>
  //Template things
</template>

<script>
  export default {
    data() {
      return {
        projectPrefix: process.env.PROJECT_PREFIX
      }
    }
  }
}
</script>

<style lang="scss">
  @import 'base/assets/styles/scss/_component-name.scss';

  //We would like to import the JUST ONE of the following stylesheets based on projectPrefix
  @import './projects/project-foo/assets/styles/scss/_component-name.scss';
  @import './projects/project-bar/assets/styles/scss/_component-name.scss';
  @import './projects/project-baz/assets/styles/scss/_component-name.scss';
  ...
</style>

At the moment, everything works fine in terms of the styles being displayed correctly per project. The problem is that we also include a bunch of unused styles in this way.

Does anyone know of a good solution for how we might be able to dynamically import a stylesheet based on an environment variable?

1 Answers

You could create a component for env variable. Something like:


<template>
  <component-with-style-a v-if="projectPrefix === 'A'" />
  <component-with-style-b v-else />
</template>

<script>
  export default {
    data() {
      return {
        projectPrefix: process.env.PROJECT_PREFIX
      }
    }
  }
}
</script>
Related