webpack2: how to import Bootstrap CSS for react-bo

2020-02-10 08:19发布

问题:

I am using webpack 2 and react-bootstrap in my project ; I can't find how to have bootstrap CSS styles properly applied it seems like the .css file is not loaded, no matter which import statement I tried to use.

As far as I understand I do not need the full bootstrap package with javascript etc. since I am using react-bootstrap ; I just need the CSS. So I added this in my main.js file:

import 'bootstrap/dist/css/bootstrap.css';

It seems to work (no error message) but the styles are not applied...

I configured the css loader in my webpack config file as described on webpack 2 documentation.

Any help would be appreciated :)

回答1:

When setting modules: true in the css-loader, the CSS is locally scoped by default, but you need them to be available globally. The simplest solution is to remove modules: true entirely. You could still use modules in your own CSS files by using :local.

But if you would like to use modules, there are some workarounds to import globals.

Defining separate rules

Instead of enabling modules for all the CSS files, you can make two different rules, that match the desired files. So let's say all CSS imports from node_modules should be treated as regular (global) CSS. The rules would look like this:

{
  // For all .css files except from node_modules
  test: /\.css$/,
  exclude: /node_modules/,
  use: [
    'style-loader',
    { loader: 'css-loader', options: { modules: true } }
  ]
},
{
  // For all .css files in node_modules
  test: /\.css$/,
  include: /node_modules/,
  use: ['style-loader', 'css-loader']
}

Of course you can be more specific in what you want to include/exclude, if you don't want the entire node_modules.

Specifying loaders inline

You can specify the loaders in the import and webpack will use those over the configured ones. You would import bootstrap as follows:

import '!style-loader!css-loader!bootstrap/dist/css/bootstrap.css';

This is just a quick workaround without having to change any config, but it's probably not desirable, especially when having multiple such cases.