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

后端 未结 1 1699
无人共我
无人共我 2020-12-17 01:59

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

相关标签:
1条回答
  • 2020-12-17 02:27

    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.

    0 讨论(0)
提交回复
热议问题