在全球范围内将sass包含在gatsby中 [英] Include sass in gatsby globally

查看:55
本文介绍了在全球范围内将sass包含在gatsby中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下项目结构:

gatsby-config.js
/src
  /components
    layout.jsx
    /button
      button.jsx
      button.scss
  /pages
  /styles
    styles.scss
    _mixins.scss
    _variables.scss

gatsby-config.js styles.scss 分别通过以下方式配置:

and gatsby-config.js and styles.scss are configured respectively in the following way:

...
plugins: [
...,
`gatsby-plugin-sass`
]
...

@import 'variables',
        'mixins';

为了访问mixin和变量,目前正在所有组件的scss文件中导入 styles.scss ,例如:

in order to access the mixins and variables, the styles.scss is being currently imported in all the components' scss files, e.g.:

//button.scss
@import './../styles/styles.scss'

这种方法有效,但是问题是,随着项目的发展, styles.scss 会被多次导入,并且这种方法似乎出了问题.是否只能导入一次 styles.scss ,并使所有组件中的所有混合和变量可用?

This approach is working, but the problem is, as the project grows, the styles.scss is being imported multiple times and seems to be something wrong with this approach. Is it possible to import styles.scss only once, and make all mixins and variables available across all the components?

推荐答案

您可以通过 gatsby-plugin-sass 到Sass的rel ="noreferrer">选项.

You are able to pass options to Sass via gatsby-plugin-sass.

以下选项将全局将 ./src/styles/_styles.scss 的内容公开给项目中的每个Sass文件,而无需显式导入.

The following options would globally expose the contents of ./src/styles/_styles.scss to each Sass file in the project, without the need to explicitly import it.

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-sass',
      options: {
        data: `@import "${__dirname}/src/styles/styles";`,
      }
    },
  ],
}


注意:这对于某些人可能是显而易见的,但值得将来的读者提及.


Note: This might be obvious to some but it's worth mentioning for future readers.

对仅包含变量,mixin,函数等的Sass文件执行此操作(除非使用了Sass功能,否则它们不会输出任何实际的CSS).否则,您将获得在整个项目中重复多次的CSS.

Only do this with Sass files that contain just variables, mixins, functions, etc (Sass features that do not output any actual CSS unless they are used). Otherwise you will end up with CSS that is repeated multiple times across your project.

示例存储库

这篇关于在全球范围内将sass包含在gatsby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆