首页 > 解决方案 > 在每个样式表配置中自动导入 sass 部分

问题描述

最近我开始使用 CSS Modules 使用 NextJS。为了消除重复,我想在每个样式表中使用 mixins、变量等自动导入部分。

使用 GatsbyJS,我发现了如何在项目的每个样式表中自动导入一些特定的 SASS 部分。设置如下所示:

{
  resolve: `gatsby-plugin-sass`,
  options: {
  data: '@import "_reset.scss", "_typography.scss", "_mixins.scss", "_extends.scss", "_themes.scss";',
  includePaths: [
    'src/styles/partials',
    ],
  },
},

现在我的 next.settings.js 看起来像这样:

const path = require("path");
const withSass = require("@zeit/next-sass");

const partials = [
  "_reset.scss",
  "_variables.scss",
  "_themes.scss",
  "_typography.scss",
  "_mixins.scss",
  "_extends.scss",
];

module.exports = withSass({

  cssModules: true,

  webpack: config => {
    config.resolve.alias["components"] = path.join(__dirname, "components");
    return config;
  },

});

如果可能的话,如何在每个样式表中自动排除部分内容?


问题的解决方案,感谢@eric-tan 回复:

所有部分都导入到一个“_utilty.scss”部分中,该部分包含在 sassLoaderOptions 中:-> 数据:导入部分本身;-> includePaths:导入的部分所在的位置。

const path = require("path");
const withSass = require("@zeit/next-sass");

module.exports = withSass({

  cssModules: true,
  sassLoaderOptions: {
    data: '@import "_utility.scss";',
    includePaths: [
      path.resolve(__dirname, "styles/"),
    ]
  },

  webpack: config => {
    config.resolve.alias["components"] = path.join(__dirname, "components");
    return config;
  },

});

标签: csswebpacksassnext.jscss-modules

解决方案


我们可以像这样使用 sass 加载器:

  {
     // Loads a SASS/SCSS file and include the partial files before compilation
     loader: 'sass-loader',
       options: {
         data:
           '@import "foo-partial";\n ' +
           '@import "bar-partial";',
           includePaths: [
             path.resolve(__dirname, '../src/assets/styles')
           ]
        }
  }

并且 nextSass 提供了sass loader 选项,你可以尝试在你的设置中组合它们。


推荐阅读