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

喜夏-厌秋 提交于 2019-11-29 04:47:50

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!