Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using webpack to load CSS files from node modules

I'm trying to use a react component that includes a css file. I'm requiring the component as usual:

var Select = require('react-select');

I'd like to know how can I require the css needed for the component.

I've already tried this:

require('react-select/dist/react-select.css');

And this:

require('react-select.css');

And none have worked.

like image 504
thitemple Avatar asked Mar 24 '16 20:03

thitemple


People also ask

How do I load a CSS file into webpack?

To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.

How do I import a CSS file into a node module?

When importing a CSS file from node_modules , you have to make sure you have the specific package installed, e.g. by running npm install bootstrap . Note that you shouldn't use a relative path to import from node_modules . You should use an absolute path and omit the node_modules directory.

How do I bundle CSS with webpack?

By default, Webpack will inline your CSS as Javascript tags that injects the CSS into the page. This sounds strange but it lets you do hot reloading in development. In production you extract them to a file using the ExtractTextPlugin, and require it with a normal link tag.


1 Answers

Make sure you have the following packages installed:

npm install style-loader css-loader --save-dev

and that your webpack configuration has this:

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

This will require and bundle any css file that you require, and I would pull their exactly how you did it:

require('react-select/dist/react-select.css');

Another workaround that works for certain is that you copy that css file, and in the html you link it by:

<link rel="stylesheet" href="/path/to/react-select.css">
like image 177
minheq Avatar answered Oct 18 '22 03:10

minheq