简体   繁体   English

如何使用环境变量在 Nuxt 中动态导入 SCSS 样式表

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

We are running Nuxt in a monorepo and things are working well.我们在 monorepo 中运行 Nuxt,一切运行良好。 We are utilizing a /base directory containing our reusable components and stylesheets, and each project has its own subdirectory within a /projects directory.我们正在使用包含可重用组件和样式表的 /base 目录,每个项目在 /projects 目录中都有自己的子目录。

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.我们的全局变量/mixins 通过@nuxtjs/style-resources 模块添加到基础nuxt.config.js,然后我们将其扩展并导入到项目自己的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.目前,就 styles 每个项目正确显示而言,一切正常。 The problem is that we also include a bunch of unused styles in this way.问题是我们也以这种方式包含了一堆未使用的styles。

Does anyone know of a good solution for how we might be able to dynamically import a stylesheet based on an environment variable?有谁知道我们如何能够基于环境变量动态导入样式表的好解决方案?

You could create a component for env variable.您可以为 env 变量创建一个组件。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM