How to properly import bootstrap 4 sass in create-react-app

Viewed 1315

Previosly I imported bootstrap in style.less like that(not using js framework):

@import "bootstrap/less/bootstrap.less";
@import "variables.less";
@import "mixins.less";
@import "main.less";
...

Now I use create-react-app and I use separate folder for each component with it's separate sass file(I was advised that it is one of the best ways).

├── components
│   ├── About
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── App
│   │   ├── App.test.js
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── Bread
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── Delivery
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── Footer
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── Header
│   │   ├── index.jsx
│   │   ├── style.css
│   │   └── style.scss
│   ├── index.js
├── _custom.scss
├── index.js

Create-react-app docs suggest to inlude this lines in scripts in package.json:

  "scripts": {
    "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
    "watch-css": "npm run build-css && node-sass-chokidar --include-path
     ...
  },

I import bootstrap in _custom.scss like that:

@import "bootstrap/scss/bootstrap.scss";

I also have custom variables in that file.

The problem is I need to import custom.scss file in every component separately to use bootstrap or custom variables, then a built css file becomes huge. I need a solution where I need to import custom.scss file once in App/style.scss. Is it possible? How experienced developers import bootstrap


I also use reactstrap and don't import bootstrap.css, if it matters.

EDIT: I'm in a developer environment, I think that in production it should be ok, since everything is bundled into single css, I didn't checked it though.

EDIT: I can't check it because I can't build with undefined variables.

1 Answers

If you use create-react-app, and define a global variable in some css file (in your case custom.scss), import it in your index.js. After that, any component of yours has your variables, mixins etc available for use without you having to import custom.scss explicitly in the component's scss.

Related