7

i'm trying to use css-loader for :local and :global styles, it's working fine, but when i try to import a librally styles globally, i get error:

Missing whitespace before :global

Here's what i trying to do in my main scss file:

:global{
  @import "~bootstrap/scss/bootstrap";
}

I want bootstrap styles be always global, so i can use .container .row and so on in my project.
My webpack config:

{
  loader: 'css-loader',
  options: {
     modules: {
      localIdentName: '[path][name]__[local]--[hash:base64:5]',
    }  
  }
},
'postcss-loader',
'sass-loader',

Am i doing something wrong? or there's other way to make bootstrap work as global

Yar Sol
  • 197
  • 2
  • 15

1 Answers1

2

For anyone that is searching the web with no solution to this (scoping bootstrap w/ css modules), I made this work as described below.

First off, there are issues with how the sass-loader loads files with certain parameters and currently there is no easy way to scope bootstrap 4 scss files, so you would have to build using their recommended ruby setup. A further explanation of this is here.

The Fix:

The easiest way I found was to import the main bootstrap CSS file from the bootstrap node modules file within the scoped selector and manually add the selector on the parent div. You have to leave the extension off or sass will convert the import to a plain css import.

main.scss file

:global {
  .bootstrap-scoped {
  @import 'node_modules/bootstrap/dist/css/bootstrap';
}

main.js

import './main.scss';
....
<div className='bootstrapScoped'>
  <button class='btn'>fake button</button>
</div>
Tim
  • 1,105
  • 13
  • 14
  • Great, thank you. But using this solution, how can I partially override bootstrap's css with my own? I figured out that I can do it only with !important, but this is not so good. – tjnk24 Jan 04 '21 at 14:44
  • If the above scoping soln' is working you just need to ensure the specificity is not higher than yours and it will work. – Tim Jan 04 '21 at 14:48
  • I was facing the same error (in a slightly different scenario) and the key to my salvation was "leave the extension off" (I'm using WebStorm and it autocompleted the extension). Thank you @Tim! – targumon Sep 02 '21 at 11:25