How to Use Webpack with React and Bootstrap
Today, I was setting up a project using Webpack, React, and Bootstrap without jQuery. What seemed like a straightforward task ended up taking more time than expected, so I’ve decided to document the steps below:
Step 1: Install All Dependencies
First, install all the required dependencies:
npm install react react-dom bootstrap react-bootstrap babel-preset-react --save
npm install webpack css-loader style-loader file-loader url-loader babel-core babel-loader babel-preset-es2015 --save-dev
Step 2: Add Loaders in webpack.config.js
Next, add the necessary loaders to your webpack.config.js
file:
var path = require("path")
var webpack = require("webpack")
module.exports = {
entry: "./main.js",
output: { path: __dirname, filename: "bundle.js" },
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["es2015", "react"],
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.png$/,
loader: "url-loader?limit=100000",
},
{
test: /\.jpg$/,
loader: "file-loader",
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff",
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&mimetype=application/octet-stream",
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader",
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url-loader?limit=10000&mimetype=image/svg+xml",
},
],
},
}
Step 3: Import Bootstrap CSS in main.js
In your main.js
file (or whatever your entry file is), import the Bootstrap CSS:
import App from "./app.jsx"
import Bootstrap from "bootstrap/dist/css/bootstrap.css"
Step 4: Import React Bootstrap in app.jsx
Finally, in your app.jsx
, import React Bootstrap components:
import React from "react"
import ReactDOM from "react-dom"
import { Button } from "react-bootstrap"
const buttonsInstance = <Button>Click me!</Button>
ReactDOM.render(buttonsInstance, document.getElementById("here"))
HTML Setup
Don’t forget to include a div
with the appropriate ID, as well as the bundle.js
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React</title>
</head>
<body>
<div id="here"></div>
<script src="bundle.js"></script>
</body>
</html>
That’s it! Feel free to reach out if you have any questions.