Gatsby: How do I get css modules working with Gatsby v2 and without module word in the name?

Created on 28 Oct 2018  路  8Comments  路  Source: gatsbyjs/gatsby

Hi there.
Who has an experience of using scss modules in Gatsby without naming files with suffix .module.css.

I do have an app that built with my own react components library (connected as submodule).

I want to use the same component base for my new landing page but couldn't figure out how can I let Gatsby know to process my Component.scss as css module w\o adding .module.scss.

stale? question or discussion

Most helpful comment

You'll need to override the webpack config for css-loader. You can look here to see the default css config.

All 8 comments

You'll need to override the webpack config for css-loader. You can look here to see the default css config.

My gatsby-node.js

const isProd = process.env.NODE_ENV === 'production';
const componentLibPath = path.resolve(__dirname, './component-library');

exports.onCreateWebpackConfig = (
  { actions, loaders },
  { cssLoaderOptions = {}, postCssPlugins, ...sassOptions },
) => {
  actions.setWebpackConfig({
    module: {
      rules: [
        {
          test: /\.s(a|c)ss$/,
          use: [
            loaders.miniCssExtract(),
            loaders.css({ ...cssLoaderOptions, modules: true }),
            loaders.postcss({ plugins: postCssPlugins }),
            {
              loader: require.resolve('sass-loader'),
              options: {
                sourceMap: !isProd,
                ...sassOptions,
              },
            },
          ],
        },
      ],
    },
    resolve: {
      alias: {
        components: componentLibPath,
      },
      extensions: ['.js', '.jsx'],
    },
  });
};

Important note:
Node will throw error Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi" if there is gatsby-plugin-sass in gatsby-config.js

UPDATE:

To fix build issue we have to check the stage and include miniCssExtract only on html stage

gatsby-node.js

const path = require('path');

const isProd = process.env.NODE_ENV === 'production';

const componentLibPath = path.resolve(__dirname, './component-library');

exports.onCreateWebpackConfig = (
  { actions, loaders, stage },
  { cssLoaderOptions = {}, postCssPlugins, ...sassOptions },
) => {
  const isSSR = stage.includes(`html`);

  const use = [
    loaders.css({ ...cssLoaderOptions, modules: true }),
    loaders.postcss({ plugins: postCssPlugins }),
    {
      loader: require.resolve('sass-loader'),
      options: {
        sourceMap: !isProd,
        ...sassOptions,
      },
    },
    {
      loader: 'sass-resources-loader',
      options: {
        resources: [
          path.resolve(__dirname, './component-library/assets/stylesheets/_variables.scss'),
          path.resolve(__dirname, './component-library/assets/stylesheets/_mixins.scss'),
        ],
      },
    },
  ];

  if (!isSSR) use.unshift(loaders.miniCssExtract());

  actions.setWebpackConfig({
    module: {
      rules: [
        {
          test: /\.s(a|c)ss$/,
          use,
        },
      ],
    },
    resolve: {
      alias: {
        'component-library': `${componentLibPath}`,
        components: `${componentLibPath}/components`,
        utils: `${componentLibPath}/utils`,
        config: `${componentLibPath}/config`,
      },
      extensions: ['.js', '.jsx'],
    },
  });
};

Hiya!

This issue has gone quiet. Spooky quiet. 馃懟

We get a lot of issues, so we currently close issues after 30 days of inactivity. It鈥檚 been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!

Thanks for being a part of the Gatsby community! 馃挭馃挏

I am having the same issue with loading scss. I have tried to copy the configuration used by @IvanKalinin above, with some slight modifications (removing resolve block, removing the resources loader), so our config looks like this:

const isProd = process.env.NODE_ENV === "production"

exports.onCreateWebpackConfig = (
  { stage, rules, loaders, plugins, actions },
  { cssLoaderOptions = {}, postCssPlugins, ...sassOptions }
) => {
  const isSSR = stage.includes(`html`)

  const use = [
    loaders.css({ ...cssLoaderOptions, modules: true }),
    loaders.postcss({ plugins: postCssPlugins }),
    {
      loader: require.resolve("sass-loader"),
      options: {
        sourceMap: !isProd,
        ...sassOptions,
      },
    },
  ]

  if (!isSSR) use.unshift(loaders.miniCssExtract())

  actions.setWebpackConfig({
    module: {
      rules: [
        {
          test: /\.s(a|c)ss$/,
          use,
          exclude: /node_modules\/(?!react-component-library)/,
        },
      ],
    },
  })
}

The error seen in the console is:

 ERROR  Failed to compile with 2 errors                               08:05:23

 error  in /Users/aington/git/react-component-library/components/basic-button/basic-button.scss

Module build failed (from ./node_modules/sass-loader/lib/loader.js):

@import "../../styles/variables";
^
      Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi"
      in /Users/aington/git/react-component-library/components/basic-button/basic-button.scss (line 1, column 1)

Hiya!

This issue has gone quiet. Spooky quiet. 馃懟

We get a lot of issues, so we currently close issues after 30 days of inactivity. It鈥檚 been at least 20 days since the last update here.

If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 馃挭馃挏

Hey again!

It鈥檚 been 30 days since anything happened on this issue, so our friendly neighborhood robot (that鈥檚 me!) is going to close it.

Please keep in mind that I鈥檓 only a robot, so if I鈥檝e closed this issue in error, I鈥檓 HUMAN_EMOTION_SORRY. Please feel free to reopen this issue or create a new one if you need anything else.

As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks again for being part of the Gatsby community!

Invalid CSS after "": expected 1 selector or at-rule, was "var content = requi"

I'm on the same page.

Was this page helpful?
0 / 5 - 0 ratings