Search code examples
csswebpacksassnext.jscss-modules

Auto-import sass partials in every stylesheet configutation


Recently I have started working with NextJS using CSS Modules. To remove repetition I would like to auto-import partials with mixins, variables, etc. in every stylesheet.

Working with GatsbyJS I found I way how to auto-import some specific SASS partials in every stylesheet in my project. Settings looked like this:

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

Right now my next.settings.js looks like this:

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;
  },

});

If it possible, how can I auto-unclude partials in every stylesheet?


Solution to the problem, thanks to @eric-tan reply:

All partials was imported in one "_utilty.scss" partial, that was included in sassLoaderOptions: -> data: importing the partials itself; -> includePaths: where the imported partial is located.

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;
  },

});

Solution

  • We can use sass loader like this:

      {
         // 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')
               ]
            }
      }
    

    and nextSass provide sass loader option, you can try to combine them in your setting.