How to use Webpack with React and Bootstrap
I was setting up a project today using Webpack, React and Bootstrap without jQuery. This supposed to be a straight forward task but turns out I have spent a bit of time to figure it out. So I’m going to document the steps as shown below:
Firstly, install all 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
Then, add the loaders in your webpack.conf.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './main.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: "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?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
},
};
Next, in your main.js (or whatever your entry file), import Bootstrap CSS:
import App from './app.jsx';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
Finally, in your app.jsx, import react bootstrap:
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'));
Not to mention you also need the div with this 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 is it! Let me know if you have any questions.