How to import a CSS file in a React Component
Asked Answered
A

11

182

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?

Algy answered 4/10, 2016 at 13:28 Comment(4)
Hey what's up :D, it's looks like only two folder above (components & src)Devotee
Hey, you're right but it still dosn't work. I noticed that i can't use import, because i can't use export within a CSS fileAlgy
using this way #39926993Scullion
I am getting error -> @media only screen and (min-width:320px) and (max-width:640px) { ^ SyntaxError: Invalid or unexpected token at Module._compile (internal/modules/cjs/loader.js:723:23)Beery
K
67

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.

Kirstinkirstyn answered 4/10, 2016 at 13:34 Comment(7)
I'm not allowed to import another module into this project. Is their another solution only working with reactjs or native js?Algy
So i think i have to use something like this: HTMLElement.styleAlgy
It looks a little bit ugly. Why aren't you allowed to add changes in bundle building?Kirstinkirstyn
It's a postprocessing for a workship about reactjs and we're told to solve the requirements with the modules included during workshipAlgy
Ok, but just wanted to mention that fetching style tags isn't importing css files as you've asked in your question. These are 2 different issues.Kirstinkirstyn
It doesn't work for me after adding this module. It shows an npm error.Sheply
What do I use if I'm only using Babel for JSX transpilation to JavaScript? Is there a Babel plugin to load CSS stylesheet files using ES6 module imports, or do I have to update the whole project to use Webpack?Sharlenesharline
M
271

You don't even have to name it if you don't need to:

e.g.

import React from 'react';
import './App.css';

see a complete example here (Build a JSX Live Compiler as a React Component).

Martel answered 24/9, 2017 at 2:47 Comment(4)
Doesn't work for me, when I try running mocha with babel register I get... I:\....css:1 (function (exports, require, module, __filename, __dirname) { .filter-bg { ^ SyntaxError: Unexpected token .Psoriasis
Or, use react-helmet and inject the css (if its a url) in the <head> tagFineman
I am importing css files import ./App.css but it adds an entry into head. Is it possible to scope the import of App.css to App component only? I know there stuff like App.module.css but I am importing an antd css file for antd component so I can not really change the name of the file.Nomanomad
this is the problem with create-react-app, it does things people expect vanilla react does, in order for react to build css, depending on what bundler you use you need a css loader or 2Footmark
K
67

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.

Kirstinkirstyn answered 4/10, 2016 at 13:34 Comment(7)
I'm not allowed to import another module into this project. Is their another solution only working with reactjs or native js?Algy
So i think i have to use something like this: HTMLElement.styleAlgy
It looks a little bit ugly. Why aren't you allowed to add changes in bundle building?Kirstinkirstyn
It's a postprocessing for a workship about reactjs and we're told to solve the requirements with the modules included during workshipAlgy
Ok, but just wanted to mention that fetching style tags isn't importing css files as you've asked in your question. These are 2 different issues.Kirstinkirstyn
It doesn't work for me after adding this module. It shows an npm error.Sheply
What do I use if I'm only using Babel for JSX transpilation to JavaScript? Is there a Babel plugin to load CSS stylesheet files using ES6 module imports, or do I have to update the whole project to use Webpack?Sharlenesharline
W
52

I would suggest using CSS Modules:

React

import React from 'react';
import styles from './table.css';

export default class Table extends React.Component {
    render () {
        return <div className={styles.table}>
            <div className={styles.row}>
                <div className={styles.cell}>A0</div>
                <div className={styles.cell}>B0</div>
            </div>
        </div>;
    }
}

Rendering the Component:

<div class="table__table___32osj">
    <div class="table__row___2w27N">
        <div class="table__cell___2w27N">A0</div>
        <div class="table__cell___1oVw5">B0</div>
    </div>
</div>
Wakeless answered 4/10, 2016 at 13:33 Comment(5)
I would add part 1 as the answer below. And you can follow my answer to test your component.Wakeless
If tried this out and it dosn't works. I've tried to include it like this: import styles from "./disabledLink.css"; and get the following error: Module not found: Error: Cannot resolve 'file' or 'directory' ./disabledLink.css in c:\Users\Basti Kluth\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-49Algy
css modules should be installed apart, github.com/css-modules/css-modulesKirstinkirstyn
And how can I write media query for such type CSS, any Idea?Reinhardt
css modules is a different thing and has a different syntax. please don't confuse people.Footmark
R
28

The following imports an external CSS file in a React component and outputs the CSS rules in the <head /> of the website.

  1. Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. In webpack.config.js:
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. In a component file:
import './path/to/file.css';
Reciprocation answered 19/3, 2018 at 9:25 Comment(3)
And I use babel to run watcher. Maybe it doesn't see into the webpack.config.js file at allDiapason
Have you installed css-loader? Also I don't see your webpack.config.js.Reciprocation
You can add more module rules in object format as rules array's value.Queasy
E
7

The solutions above are completely changed and deprecated. If you want to use CSS modules (assuming you imported css-loaders) and I have been trying to find an answer for this for such a long time and finally did. The default webpack loader is quite different in the new version.

In your webpack, you need to find a part starting with cssRegex and replace it with this;

{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true,
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}
Edelweiss answered 14/9, 2019 at 23:21 Comment(1)
#53572700 Alternate solutionHint
J
5

You can import css file if css file reside in a same folder where you want to import than just simple try this

import './styles.css'

if css file is far away from our component that navigate that place where file is reside and use this like

import '../mainstyles/styles.css'

Jilolo answered 15/1, 2022 at 4:57 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Liberalize
B
1
  1. Install Style Loader and CSS Loader:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. Configure webpack

    module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader'
                }, {
                    test: /\.css$/,
                    loader: 'css-loader',
                    query: {
                        modules: true,
                        localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            ]
        }
    
Bowker answered 7/6, 2018 at 12:53 Comment(0)
M
1

In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:

const btnStyle = styledImport.react('../App.css', '.button')

// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.

NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.

Moderato answered 21/12, 2018 at 15:28 Comment(0)
Y
1

You can also use the required module.

require('./componentName.css');
const React = require('react');
Yippie answered 23/7, 2019 at 20:12 Comment(0)
M
0

Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:

webpack.config.js Import extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js Make instance of the plugin

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like

body {
    background: red;
}

My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor

Mohandas answered 4/8, 2020 at 11:12 Comment(0)
B
-3

You can import your .css file in .jsx file

Here is an example -

import Content from '../content/content.jsx';
Benares answered 29/10, 2019 at 8:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.