Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

webpack2: how to import Bootstrap CSS for react-bootstrap to find its styles?

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...