Setting up Bootstrap 4 SCSS with React webpack: A comprehensive guide

Embarking on a new project with ReactJS ES6 and webpack.

Utilizing the react-static-boilerplate starter. My main query lies in how to import Bootstrap4 into the build process?

Avoiding the use of the generated bootstrap.css file, I aim to have webpack construct it instead. This way, I can easily modify its @variables, apply my theme, and more.

The initial steps involved cloning the boilerplate:

> git clone -o react-static-boilerplate -b master --single-branch \
      https://github.com/kriasoft/react-static-boilerplate.git MyApp
>cd MyApp && npm install
  1. Installed bootstrap via npm.

    npm install [email protected]

Upon requiring the primary bootstrap file into my index.js, it loads seamlessly. However, I'm curious about including the sass files of Bootstrap to kickstart customization. Any guidance on this front would be greatly appreciated.

Answer №1

To begin, start by acquiring the appropriate loader for scss files.

Install sass-loader using the following command:

npm install sass-loader --save-dev

Next, configure your webpack to handle all scss files. Here is how you can do it:

{test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ]}

If encountering an error related to node-sass:

If you come across an error such as "cannot resolve node-sass," install it with:

npm i node-sass --save-dev

Now, when importing bootstrap.scss, webpack will bundle it for you:

import "bootstrap/scss/bootstrap.scss"

Customizing the styles:

For example, in your own scss file:

$btn-font-weight:bold;

Then, import the component you wish to override or the entire bootstrap.scss:

@import '~bootstrap/scss/bootstrap.scss';

In my scenario, style.scss looks like this:

$btn-font-weight:bold;
@import '~bootstrap/scss/bootstrap.scss';

In your main.js file:

import "bootstrap/scss/bootstrap.scss"
import "./style.scss"

This guide should help you reach your desired outcome!

A demo application I created can be found here

After running npm install, execute npm start and navigate to localhost:8080

Answer №2

Looks like the template is missing the sass-loader and isn't checking for .scss files.

To fix this, start by installing npm i sass-loader --save

Next, in the webpack config under the loaders section, add the following:

webpack.config.js

var path = require('path');
var nodeModules = path.resolve(path.join(__dirname, 'node_modules'));
// complete configuration object
const config = {
    // ...
    loaders: [
        // ...
        {
            test: /\.(css|scss)$/,
            include: [
                path.join(nodeModules, 'bootstrap'),
            ],
            loaders: ["style", "css", "sass"]
        }
    ]
    // ...
};

If you want to customize bootstrap's .scss variables, you can do so like this:

styles/app.scss

$brand-warning: pink !default;
@import '~bootstrap/scss/bootstrap.scss';

In your main.js, remember to import the stylesheet

import "styles/app.scss";

It's worth mentioning that this solution is similar to one provided in this answer

Answer №3

After making the switch to react-slingshot with webpack already configured for sass, you can streamline the process a bit. Simply add Bootstrap 4 using npm as follows:

npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c0e03031808190b02104d49475d434d435c55554887"><span class="__cf_email__" data-cfemail="7f161a1a01101002101434105846584605">[email protected]</span></a> --save

Next, in src/styles/styles.scss, include these two imports:

@import "./bootstrap-custom";
@import "~bootstrap/scss/bootstrap";

This approach is similar to what @DanielDubovski has demonstrated, but it's considered more standard practice to have a separate file for bootstrap overrides. Removing the default settings is necessary since you'll be customizing Bootstrap's defaults and avoiding accidental alterations to your custom bootstrap colors. To begin working on src/styles/bootstrap-custom.scss, refer to node_modules/bootstrap/scss/_variables.scss for a comprehensive list of default variables. From there, you can select the variable names that require modification. Here's an example snippet from bootstrap-custom.scss focusing on greyscale color overrides:

/*
 * Custom overrides for Bootstrap defaults - additional overrides can be added here, consult node_modules/bootstrap/scss/_variables.scss for a full list
 */

 $gray-dark:                 #333;
 $gray:                      #777;
 $gray-light:                #000;
 $gray-lighter:              #bbb;
 $gray-lightest:             #ddd;

Answer №4

Use this command to install the necessary dependencies for Sass in your project: 
npm install --save-dev sass-loader css-loader style-loader node-sass

To configure the usage of Sass in your webpack.config.js file, add the following code snippet:

 loaders: [
     {
         test: /\.scss$/,
         loaders: [ 'style', 'css', 'sass' ]
     }
 ]
 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Caption image on hover

Is it possible to make an image overlap text on a horizontal menu bar when hovering with the mouse? I am designing a horror website and would like a bloody handprint to appear over the links in the menu bar when they are hovered over. I know this can be do ...

Enable the ability for anchor links to be clickable when the CSS media print format is used to generate

To illustrate: <a href="https://www.google.com">Google anchor link</a> on the website, it displays as: Google anchor link When printed, it shows as: Google anchor link(https://www.google.com) To address this issue, I included in the CSS: ...

Require the implementation of seamless scrolling when clicking on an anchor tag with a specific ID, as opposed to the abrupt jumping to the corresponding

<div id="slider"> <div id="pro1"></div> <div id="pro2"></div> <div id="pro3"></div> </div> <div id="thumb"> <a href="#pro1"> <img id="tpro1" src="projects/tpro5.jpg" style="hei ...

What is causing the lack of category options to appear in the select menu?

I've been trying to populate a select menu with categories from the database using this code, but it doesn't seem to be working as expected. <select onChange={handleChange("category")} className="form-control&quo ...

Issue with React component not updating content after state changes in Next.js framework

Currently, I am facing an issue with my Header component not updating its content on state change. The goal is to show the user's Profile once the state changes, but unfortunately, it does not update immediately; it only changes after a page refresh o ...

Encountering the error "Compiled with issues" upon starting the react server

Hello everyone, I'm currently in the process of upgrading from React 16 to 18. At the moment, I am using Material UI 4.11 but will be upgrading to V5 soon. However, when I start using 'npm start' after upgrading React, I encounter the errors ...

Using the componentDidUpdate lifecycle method to update the state in React

Having trouble updating the state in my code I'm encountering a problem with my componentDidUpdate() function, as it's not successfully updating the state of assignments after I make an API call to update them. Specifically, when updating the ex ...

Set the width of the left div in percentage and have the right div automatically fill

In my layout, I have a left div with a percentage width floating to the left, and a right div also floating left that should take up the remaining space. Here is a [fiddle] link for reference: https://jsfiddle.net/gfhfku8k/. Any assistance would be great ...

Exploring techniques for monitoring untracked files within node_modules directory while focusing on distinguishing key elements

t Hey there, Currently in the process of building a react template from scratch using visual studio code, I noticed that within the node_modules folder there is a .bin folder with untracked files. The green dot indicates that these untracked files are hig ...

The integration of ag-grid webpack css is not reflecting on the website as intended

I'm facing an issue with ag-grid in my react application where I can't seem to get the CSS working properly with webpack. The grid is currently displaying like this: image: https://i.sstatic.net/RPKvH.png const path = require("path"); var webp ...

The Access-Control-Allow-Origin CORS header is missing in React JS, resulting in a status code of 401

Having an issue with sending the access token in the header using Axios. I'm getting the following error: The request to 'http://192.168.0.254:3333/api/DOTMobileApi/test' from origin 'http://localhost:3000' has been blocked by COR ...

Adjusting the image to fit the container based on its shorter side, regardless of the image's orientation

I have a square container with a predetermined size. I want to place an image inside the container so that its smaller side fits perfectly with the parent container, while the larger side extends beyond the edges of the container without distorting the ima ...

What is the reason for the varying sizes of my buttons and the irregular alignment of their contents?

Take a look at this demo using Bootstrap 4 and Material icons : https://i.sstatic.net/fdpr2.png It appears that only the first button is properly sized and its icon aligned correctly, while all icons are of the same size. I have observed that by removin ...

Can you explain the functionality of this: http://welbog.homeip.net/ ?

Can you explain how this operates?: All you need to do is scroll down. The design is impressive, absolutely impressive, and it functions seamlessly without the use of javascript. How is that possible? ...

React error: File undefined (cannot be exported)

Encountering an issue while attempting to follow a tutorial: src/components/MyApp.js Line 17:18: 'myApp' is not defined no-undef Search for the keywords to learn more about each error. This is what my myApp.js file contains: import React fr ...

In React hooks, you can easily deactivate an image element upon the first click on a toggle, and then reactivate it using setTimeout

I am currently working on a feature for parking slot allocation based on reservation time. The main goal is to allow users to click on an image element which will toggle to a second image and then disable the toggle functionality for a set period of time ( ...

Maintaining the size and proportions of an object as it

I'm currently learning the ins and outs of HTML/CSS while working on a navigation bar. However, I've run into an issue with scaling. Here is the website in full-screen mode.https://i.sstatic.net/kCFqn.png Here is the website when it's sligh ...

Ensure that the text inside the button does not exceed its boundaries (utilizing Bootstrap v4)

My current code snippet appears below. <div class="col-xl-2 col-lg-12"> <button class="btn btn-secondary w-100" value=1>But.</button> </div> <div class="col-xl-4 col-lg-12"> <button cla ...

There was a problem retrieving the product information from the API

I have been struggling to pinpoint the exact issue at hand. The foundation of HTML and CSS is pre-written, with JavaScript responsible for generating the core elements to populate the DOM. Within my script, I am attempting to retrieve product data in ord ...

Tips for implementing a custom hook in the submission function of a React hook form

Currently, I'm tackling the issue with the next 13 tasks using the react hook form. One custom hook has been developed inside the hook folder named src/hooks/use-api.ts for handling global API functionalities like useGet, usePost, and more. The probl ...