What is Webpack ?
Webpack is a tool that bundles your modern day JavaScript application with multiple file imports like in case of React project into a single or in some cases multiple JS bundle files.
for example
Let’s start with the setup, first you will have to create node project.
mkdir my-app
cd my-app
npm init -y
Open your package.json file and insert below commands in the scripts section. This are command to build and start development server.
"scripts": {
"build": "webpack --mode production",
"webpack-dev-server": "webpack-dev-server",
"dev": "webpack-dev-server --mode=development",
"prod": "webpack --mode=production"
},
Install all webpack module that we would need for the project.
npm install webpack
npm install webpack-cli
npm install webpack-dev-server
Create a webpack configuration file webpack.config.js. This config would create bundle called ‘bundle.js’ in a new folder ‘dist’.
Next step is to inform webpack that you have to add newly create bundle.js file to <script> tag within the main html page and you do that by installing below two plugins.
npm install html-webpack-plugin
npm install html-loader
Now our webpack.config.js file would look like
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
entry: './src/App.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: { loader: "babel-loader" }
},
{
test: /\.html$/,
use: { loader: "html-loader" }
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
]
};
What is Babel ?
Babel is a JavaScript compiler that compiles ECMAScript 2015+ into javascript which can be understood by older and current browsers.
npm install @babel/core
npm install babel-loader
npm install @babel/preset-env
npm install @babel/preset-react
We need to create a .babelrc file and insert below config.
{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
Install React
Now we need to setup react project
mkdir src
cd src
touch App.js
touch index.html
npm install react
npm install react-dom
App.js
import React from "react";
import ReactDOM from "react-dom";
const App = () => {
const message = "Hello World";
return (
<div>
<div>{message}</div>
</div>
);
};
ReactDOM.render(<App />, document.querySelector("#root"));
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My-App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
Now that we have created the setup lets run and build project.
npm run dev //it will run development server with hot reloading enabled
npm run build //this command would build your project for you
Done ! Your React project setup is ready. Happy Coding.