Search code examples
javascriptreactjsrelative-path

How to import a CSS file in a React Component


I want to import a CSS file into a react component.

I've tried import disabledLink from "../../../public/styles/disabledLink"; but I get the error below;

Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2

C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css is the location of the CSS file I'm trying to load.

To me it seems like import is not looking up the correct path.

I thought with ../../../ it would start to look up the path three folder layers above.

C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js is the location of the file that should import the CSS file.

What am I doing wrong and how can I fix it?


Solution

  • You need to use css-loader when creating bundle with webpack.

    Install it:

    npm install css-loader --save-dev
    

    And add it to loaders in your webpack configs:

    module.exports = {
      module: {
        loaders: [
          { test: /\.css$/, loader: "style-loader!css-loader" },
          // ...
        ]
      }
    };
    

    After this, you will be able to include css files in js.