reactjswebpackjsxwebpack.config.js

How to properly load CSS from an external module in React?


In my react.js app I am trying to use an external module (React Toastify) using the following statement:

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

Unfortunately this throws the following error:

Uncaught Error: Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
> .Toastify__toast-container {
|   z-index: 9999;

I guess it has something to do with webpack, here are my settings in webpack.config.js:

    output: {
  filename: '[name].js',
  path: path.resolve(__dirname, 'assets'),
},

devtool: production ? '' : 'source-map',

resolve: {
  extensions: [".js", ".jsx", ".json"],
},


module: {
  rules: [
    {
     test: /\.jsx?$/,


      exclude: /node_modules/,



      loader: 'babel-loader',
    },
  ],
},

};

I am not sure how this can be fixed, any advice appreciated.


Solution

  • In your webpack config file you have add the css loader test:

    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
        }, {
          test: /\.css$/,
          use: ['style-loader', 'css-loader'],
        },
      ],
    },
    

    And don't forget to install it with npm i -D css-loader.

    More info here: https://github.com/webpack-contrib/css-loader