All of us have used CRA(create-react-app) when we worked with React. Its an awesome tool. It gives us just to focus on React by letting take care of the configuration. Today we are going to learn how to setup Webpack and Babel for our React app.
First lets learn about Webpack and Babel.
Its a module bundler which lets us bundle our project files into a single file. It requires a webpack.config.js file in the root folder. Where we tell our webpack how to work with our application by giving entry point information and also output information.
const path = require('path');
module.exports = {
entry: './src/app.js', // relative path
output: {
path: path.join(__dirname, 'public'), // absolute path
filename: 'bundle.js' // file name
}
};
Entry point is where does our application going to kick off and we set it by giving relative path value. And the output property tells webpack where to emit the outputs it creates and how to name those files. We have to give absolute path value in our output path properties.
Its a JavaScript compiler. Babel on its own actually has no functionality. Yeah its a compiler but its not going to compile anything by default. We have to add various pulgins and presets to add support particular language features. You can check this out by visiting Babel website. In babel website navigation bar section you will find Try It Out. Click on it and you will get a new window.
Where in left side window you can write your code and in right side window you will get your compiled code. Now lets write some JSX in left side window.
const template = <p>Hello</p>;
In right side window you will get JavaScript understandable compiled code which is always run behind the scene in our React app. In left side you see some PRESETS options where some options are already been ticked. If you now untick react presets option you will see an error cause this react-preset is responsible for converting our JSX syntax into JavaScript understandable code.
In our tutorial we are going to use two presets:
Now we know little bit about webpack and babel. Lets dive into our React setup.
mkdir react-setup-tutorial
cd react-setup-tutorial
mkdir public src
touch public/index.html src/app.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
npm init -y
npm install webpack webpack-cli --save-dev
We installed webpack-cli so that we can use webpack in the command line.
We already know that webpack needs webpack.config.js file in the root of the project directory. So lets create webpack.config.js file with the following code inside it.
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
}
};
Next add the webpack command inside package.json:
"scripts": {
"start": "webpack --mode=development",
"build": "webpack --mode=production"
}
There are two modes in Webpack, development and production. Which we can set by --mode flag. Production mode produces optimize files which are ready for use in production.
Install React:
npm install react react-dom
Now import react and react-dom inside our app.js file and also add some react code.
import React from 'react';
import ReactDOM from 'react-dom';
const template = React.createElement('p', {}, 'Hello from react');
ReactDOM.render(template, document.getElementById('root'));
Now use below command in your terminal and open your index.html file in your browser.
npm start
Your app is working well. But you have question why didn't we use JSX. This time lets try with some JSX code in our app.js file.
import React from 'react';
import ReactDOM from 'react-dom';
const template = <p>Hello from react</p>;
ReactDOM.render(template, document.getElementById('root'));
Now again run our previous command.
npm start
This time you will get an error. That's because we use JSX and JavaScript doesn't support JSX. So If we want to use JSX in our app we need to compiled it. And we can do it by babel.
npm install @babel/core @babel/preset-env @babel/preset-react babel-loader --save-dev
We already know about @babel/preset-env and @babel/preset-react. Now what is @babel/core and babel-loader.
Lets configure babel by creating a .babelrc file inside the root of the project directory with following contents inside of it.
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
This file will tell babel which presets to use for transpiling the code.
Now its time to teach webpack how to compile JSX into JavaScript code. To do that we need to use loader. A loader let us customize the behavior of webpack when it loads a certain files. Its going to run certain files through babel. For that we need to setup loader in webpack.config.js file via the module property on our objects. module property needs an array of rules and a rule let us define how we want to use our loaders. Now we have one rule to take JSX and convert it into JavaScript with babel.
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
}
};
Here we set one rule of object where loader property tells which loader we want to use and we use babel-loader. test property for what files do we actually want to run this loader on and we want to run it on files that ends up with .js. exclude property to exclude a set of files and we use /node_modules/ cause we don't want to run babel through those libraries. Now we can use JSX in our React. Lets run our app again.
npm start
This time we don't get any error. Open your index.html file in the browser and yeah its working.
Lets add some extra configuration settings in our webpack.config.js file.
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
devtool: 'cheap-module-eval-source-map'
};
Here we setup Source map by using devtool property. It enhance our debugging process. Its use to display our original JavaScript while debugging, which is lot easier to look at than minified code.
Run this below command in the terminal.
npm install webpack-dev-server --save-dev
Add following code inside webpack.config.js file.
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
devtool: 'cheap-module-eval-source-map',
// changed line
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
Next add webpack-dev-server command inside package.json:
"scripts": {
"start": "webpack --mode=development",
"build": "webpack --mode=production",
"dev-server": "webpack-dev-server"
}
Now run this command.
npm run dev-server
Its going to start development server. And It gives us output where we can access it. Now we have integrated both tools into one, the dev server is our server and its also running webpack for us.
Now we can visit the highlighted url and we will get our app.
Lets create a new file and folder in the src directory.
Use following command to create file and folder.
mkdir src/styles
touch src/styles/styles.css
Now add following styles inside styles.css file.
* {
color: blue;
}
To load our style.css file we need to setup new rules in webpack.config.js file.
Before that we need to install some new loader.
npm install css-loader style-loader --save-dev
Now add new rules in our webpack.config.js file.
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
// New rules to load css
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
import style.css inside our app.js file and run dev-server to see the effect.
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/styles.css';
const template = <p>Hello from react</p>;
ReactDOM.render(template, document.getElementById('root'));
If we want to use SCSS then we need to install sass-loader that would help webpack to compile sass to css. The sass-loader is dependent on another package node-sass.
npm install sass-loader node-sass --save-dev
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
// Rules to load scss
{
// Some change here
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
devtool: 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public')
}
};
Now change our style.css file extension .css to .scss that is style.scss.
Alos change the css import in app.js to:
import './styles/styles.scss';
And add following style to see that our wepback is working correctly for SASS.
$brand-color: blue;
* {
color: $brand-color;
}
Now run dev-server again by using following command.
npm run dev-server
And we configure our webpack for SASS.
That's it. Now we have configure Webpack and Babel for React that we can use to create our React projects. Thanks for reading and stay tuned.🙂
Previously published at https://dev.to/iamismile/how-to-setup-webpack-and-babel-for-react-59ph