How to import stylesheets from node_modules in sass loader without "~"

Viewed 5744

I'm setting up my Storybook instance to load the styles from my Rails app but it failed to load the imports within my main.scss file, both are stylesheets from node_modules:

@import 'react-table/react-table.css';
@import 'animate.css';

I received errors when I try to run my storybook instance:

ERROR in ./app/javascript/stylesheets/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--9-2!./app/javascript/stylesheets/main.scss)
Module not found: Error: Can't resolve './animate.css' in '<my_project>/app/javascript/stylesheets'
 @ ./app/javascript/stylesheets/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--9-2!./app/javascript/stylesheets/main.scss) 4:40-111
 @ ./app/javascript/stylesheets/main.scss
 @ ./stories/1-Table.stories.js
 @ ./stories sync ^\.\/(?:(?:(?!\.)(?:(?:(?!(?:|\/)\.).)*?)\/)?(?!\.)(?=.)[^\/]*?\.stories\.js\/?)$
 @ ./.storybook/generated-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true

ERROR in ./app/javascript/stylesheets/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--9-2!./app/javascript/stylesheets/main.scss)
Module not found: Error: Can't resolve './react-table/react-table.css' in '<my_project>/app/javascript/stylesheets'
 @ ./app/javascript/stylesheets/main.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js??ref--9-2!./app/javascript/stylesheets/main.scss) 3:40-127
 @ ./app/javascript/stylesheets/main.scss
 @ ./stories/1-Table.stories.js
 @ ./stories sync ^\.\/(?:(?:(?!\.)(?:(?:(?!(?:|\/)\.).)*?)\/)?(?!\.)(?=.)[^\/]*?\.stories\.js\/?)$
 @ ./.storybook/generated-entry.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/generated-entry.js (webpack)-hot-middleware/client.js?reload=true&quiet=true

This is the directory of part of my working project:

.
├── .storybook
│   ├── main.js
│   └── preview-head.html
├── app
│   ├── assets
│   │   └── stylesheets
│   │       ├── _base.scss
│   └── javascript
│       ├── packs
│       │   ├── application.js
│       │   └── server_rendering.js
│       └── stylesheets
│           ├── _variables.scss
│           └── main.scss
├── babel.config.js
├── postcss.config.js
├── stories
│   ├── 0-Welcome.stories.js
│   └── 1-Table.stories.js
├── yarn-error.log
└── yarn.lock

And this is my attempt in my Storybook's main.js to let sass-loader know I want to import the files without putting the "~" sign as the web app side will not load the styles correctly so it's not an option to change the webpack config of my project.

const path = require('path')

module.exports = {
  stories: ['../stories/**/*.stories.js'],
  addons: ['@storybook/addon-actions', '@storybook/addon-links'],
  webpackFinal: async config => {
    config.module.rules.push({
      test: /\.scss$/,
      use: [
        'style-loader',
        'css-loader',
        {
          loader: 'sass-loader',
          options: {
            includePaths: [
              '../node_modules/animate',
              '../node_modules/react-table'
            ]
          }
        }
      ],
      include: [
        path.resolve(__dirname, '../node_modules'),
        path.resolve(__dirname, '../app/javascript/stylesheets'),
        path.resolve(__dirname, '../app/assets/stylesheets')
      ]
    })
    return config
  }
}

Am I doing it wrongly?

2 Answers

If you are using Webpack 4.x, then all that you need is to add a couple of aliases in your Webpack config file like this:

// Your Webpack config file
...

webpackFinal: async config => {
  config.module.resolve.alias = {
    'animate-css': path.resolve(__dirname, '../../../node_modules/animate.css'),
    'react-table': path.resolve(__dirname, '../../../node_modules/react-table-v6/react-table.css'),
  }

  ...
}

and then you can import these aliases in your main.scss:

@import 'animate-css';
@import 'react-table';

You also need to remove options from your sass-loader. I specified paths to node_modules assuming it is on the same level as your app directory, also package react-table contains no CSS file, so I specified v6.

Complete working Webpack 5 example with includePaths

Here's a complete example, not sure why includePaths didn't work for OP, or if there were other restrictions, but it did the trick for me, as I'm able to directly @use "normalize.css/normalize.css" from main.scss without the tilde.

This produces dist/main.css which is a minified CSS containing both:

  • our main.scss
  • normalize.css via node_modules

The effect of both can be seen on the index.html test file.

webpack.config.js

const path = require('path');

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const nodeModulesPath = path.resolve(__dirname, 'node_modules');

module.exports = {
  entry: {
    main: ['./main.scss'],
  },
  mode: 'none',
  module: {
    rules: [
      {
        test: /\.(scss|css)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: "sass-loader",
            options: {
              sassOptions: {
                includePaths: [nodeModulesPath],
              },
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
  ],
  optimization: {
    minimizer: [
      new CssMinimizerPlugin(),
    ],
    minimize: true,
  }
};

main.scss

@use "normalize.css/normalize.css";

body {
  background-color: red;
}

index.html

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Sass import</title>
<link rel="stylesheet" href="dist/main.css">
</head>
<body>
<p>Hello</p>
</body>
</html>

package.json

{
  "name": "webpack-cheat",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "webpack",
    "sass": "rm -f dist/main.css && sass main.scss dist/main.css"
  },
  "author": "Ciro Santilli",
  "license": "MIT",
  "devDependencies": {
    "css-loader": "5.2.4",
    "css-minimizer-webpack-plugin": "3.0.2",
    "mini-css-extract-plugin": "2.1.0",
    "normalize.css": "8.0.1",
    "sass": "1.32.11",
    "sass-loader": "11.0.1",
    "style-loader": "2.0.0",
    "webpack": "5.36.1",
    "webpack-cli": "4.6.0",
    "webpack-dev-server": "3.11.2"
  }
}
Related