Getting Started with React, Webpack and Bootstrap
ReactJs have been around for quite a while now but starting out as a react developer is not really easy. As a developer, you just want to install the library, dependencies, setup your development environment and start doing what you know how to do best (coding).
For React, you have to jump over a few hurdles before you quite settle in with developing or experimenting. Setting up your development environment can take few hours to a few days. It gets really annoying setting up instead of building your solution. I have been there and it wasn’t funny.
There are lots of React tutorials and the official one here provides a very smooth way of getting started with ReactJs but for an experienced developer, this is not good enough. You will want to adopt best practices, use the tools you know and structure your react project in certain way.
I am a big fan of Bootstrap and Fontawesome; I love to include these libraries in most of my web projects. With the latest release of Bootstrap 4 and Fontawesome in 2018, there is really so much you can achieve with minimal effort using these tools. Webpack is the tool I have come to love and it is an amazing tool that makes life a lot easier for the developer. You can read more about these tools on their respective websites.
In this article, we will be looking at
- Creating a ReactJs project from Scratch
- Setting module bundler (Webpack) with auto bundle on save and browser reloading
- Integrating Bootstrap in your project
- Adding fontAwesome to your project (later)
You may clone the React Webpack Starter project on github and try it out
Now lets get started…
Create React Project
Using your terminal or Command prompt, navigate to the location that you want to store your project files and create a directory with this command: mkdir react-project
Navigate into your new project cd react-project
Initialize node project with npm init
and follow the prompts to provide required information (if you don’t have NodeJs installed on your machine, head to NodeJS website, download the version for your OS and install)
Install Packages
We need to install a couple of global packages that will help with transpiling our code and bundling assets to ES6 standards. We need to install babel and webpack
npm install babel babel-cli webpack webpack-cli webpack-dev-server-g
Now we proceed to install React and babel plugins locally
npm install react react-dom --save
Install babel plugins locally only on dev
npm install babel-core babel-loader babal-react babel-preset-env --save-dev
Let’s install some more modules for enhancement
npm install path open-browser-webpack-plugin --save-dev
The path
module helps you resolve directories while the browser plugin enables auto-browser launch after compiling assets. Enough with these installations. Lets get to work.
Directory Structure
In building reactive frontend apps, it has become common practice to separate src
directories from public accessible directories. I chose to adopt the directory structure below because it feels good for me. You can however adjust it to suit your preferred style.
react-project- dist - assets bundle.js index.html- node_modules- src App.jsx index.js.babelrcpackage.jsonwebpack.config.js
Basically, we will add a couple of files and two directories to our project root. You will find all installed node modules in node_modules, already created during installation.
It will be cool to open the directory on your favourite text editor pr IDE and create two directories src
and dist
in the root of your project.
create .babelrc
in the project root and add this code
// .babelrc{ "presets": ["env"]}
create webpack.config.js
and add this code to it
// Import webpack modulevar webpack = require("webpack");
// Import open browser pluginvar OpenBrowserPlugin = require('open-browser-webpack-plugin');
//Import path moduleconst path = require('path');
module.exports = { entry: "./src/index.js", //set entry file
// Resolve to output directory and set fileoutput: { path: path.resolve("dist/assets"), filename: "bundle.js", publicPath: "assets"},
// Add Url param to open browser plugin
plugins: [new OpenBrowserPlugin({url: http://localhost:3000'})],
// Set dev-server configurationdevServer: { inline: true, contentBase: './dist', port: 3000},
// Add babel-loader to transpile js and jsx files
module: { rules: [{ test: /\.jsx?$/, exclude: /(node_modules)/, use: [ {loader: 'babel-loader'}, query: {presets: ["react"]} ] }] }
}
Navigate to the src
directory and add two files
//Filename ./src/index.js// Import resourcesimport React from 'react';import ReactDOM from 'react-dom';import App from './App.jsx';
// Render main appReactDOM.render(<App/>, document.getElementById('app'));
Add content to App.jsx
//Filename ./src/App.jsx// Import react
import React from 'react';
class App extends React.Component {
render() {return (<div><h1>Hello World in React</h1></div>);}}
export default App;
Then move further to setup our distribution directory and add the ./dist/assets
directory and index.html
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>React Project Starter</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="assets/bundle.js"></script>
</body></html>
That should be all for now. Verify that your files are in the right directory then head to package.json
to make some adjustments and launch. In the scripts section, delete tests and replace the scripts with this..
..."scripts": {
"start": "webpack-dev-server --hot --mode development"
},...
We all set now to launch. On your terminal, navigate to the project directory react-project
and run this command
npm start
Webpack will go ahead and bundle your assets and save in bundle.js
then launch your browser on localhost:3000
and you should see this if everything went well
Now that we have our basic setup working, it is time to add bootstrap to our project and make it responsive.
npm install bootstrap --save
Bootstrap has dependencies and we need to also install webpack loaders for styles
, sass
etc. Lets install the javascript dependencies first
npm install jquery popper.js --save
Then we install webpack loaders
npm install style-loader css-loader postcss-loader precss autoprefixer sass-loader --save
Now we make a few changes and our Bootstrap will be up and running
First we import bootstrap resources in index.js
and it now becomes
// Import resources
import React from 'react';import ReactDOM from 'react-dom';import App from './App.jsx';
// Import bootstrap cssimport 'bootstrap/dist/css/bootstrap.min.css';
// Render main app
ReactDOM.render(<App/>, document.getElementById('app'));
Then we update webpack.config.js
to add style and css loaders like so
// Import webpack modulevar webpack = require("webpack");
// Import open browser pluginvar OpenBrowserPlugin = require('open-browser-webpack-plugin');
//Import path moduleconst path = require('path');
module.exports = { entry: "./src/index.js", //set entry file
// Resolve to output directory and set fileoutput: { path: path.resolve("dist/assets"), filename: "bundle.js", publicPath: "assets"},
// Add Url param to open browser plugin
plugins: [new OpenBrowserPlugin({url: http://localhost:3000'})],
// Set dev-server configurationdevServer: { inline: true, contentBase: './dist', port: 3000},
// Add babel-loader to transpile js and jsx files
module: { rules: [{ test: /\.jsx?$/, exclude: /(node_modules)/, use: [ {loader: 'babel-loader'}, query: {presets: ["react"]} ] }, {
test: /\.css$/, use: ['style-loader', 'css-loader'] }
] }
}
Lastly, we update App.jsx
with bootstrap jumbotron to test like so
//Filename ./src/App.jsx// Import react
import React from 'react';
class App extends React.Component {
render() {return (<div><h1>Hello World in React</h1></div><div class="jumbotron">
<h1 class="display-4">Amazing React, Bootstrap and Webpack</h1>
<p class="lead">Created with love</p>
<hr class="my-4"/>
<p>It uses utility classes for typography and spacing to space content out
within the larger container.</p>
<p class="lead">
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</p>
</div>
);}}
export default App;
Now you should see this nice looking page
Congratulations
So far we have been able to setup React, Webpack and Bootstrap 4. I hope to follow up this article with some more updates on building with react in the next few days.
Feel free to clone the repo and play around with it. Happy Hacking