Hands up if you've ever built a React project with Create React App (CRA) - and that's all of us, isn't it? Now, how about we pull back the curtain and see what's actually going on behind the scenes? Buckle up, it's time to understand what CRA really is and explore the wild, untamed world of creating a React project without it. Sounds exciting, huh? It is.
What is CRA?
CRA - Create React App (https://create-react-app.dev/) - is a command line utility provided by Facebook for creating react apps with preconfigured setup. CRA provides an abstraction layer over the nitty gritty details of configuring tools like Babel
and Webpack
. It allows us to focus on writing code. Apart from this, it basically comes with everything preconfigured and developers don’t need to worry about anything but code.
Well, that is well and good. Why do we even need to learn about manual configuration then? Well, at some point in your career, you’ll need to deal with webpack config and tweak it. And if that’s not enough, how about for some curiosity? 🙂
Let us understand what wepack and babel are.
Webpack:
As per the official docs (https://webpack.js.org/concepts/)
“At its core, webpack is a static module bundler for modern JavaScript applications.”
But what does that actually mean? Let’s break it down:
static
: It refers to the static assets (HTML, CSS, JS, images) on our application.
module
: It refers to a piece of code that is in one of our files. Usually in a large application, it’s not possible to write up everything in a single file, so we have multiple modules that are later piled up all together.
bundler
: Bundler is a tool (which is webpack in our case), that bundles up everything we have used in our project and converts them to native, browser understandable js, css, html (static assets)
source: https://webpack.js.org/
So, in essence, webpack takes our application's static assets (like JavaScript modules, CSS files, and more) and bundles them together, resolving dependencies and optimizing the final output.
Webpack is preconfigured in our Create-React-App (CRA), and for most use cases, we don't need to adjust it. You'll find that many tutorials begin a React project with CRA. However, to truly understand Webpack and its functionalities, we need to configure it ourselves. In this guide, we'll attempt to do just that.
Let’s break this whole process into multiple steps:
Step 1: Let us name our new project
Create a new project folder and navigate into it.
mkdir react-webpack-way
cd react-webpack-way
Step 2: Initialize npm
Run the following command to initialize a new npm project. Answer the prompts or press Enter to accept the default values.
npm init # if you are patient enough to answer the prompts :)
Or
npm init -y
This will generate a package.json
for us.
Step 3: Install React and ReactDOM
Install React and ReactDOM as dependencies.
npm install react react-dom
Step 4: Create project structure
You can create any folder structure that you are used to. But for the sake of simplicity, let’s stick to the following structure:
|- src
|- index.js
|- public
|- index.html
Step 5: Set up React components
Let’s populate our index.js
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return <h1>Hello, React with Webpack!</h1>;
};
ReactDOM.render(<App />, document.getElementById('root'));
Step 6: Let’s deal with the HTML file
Add the following content to index.html
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>React with Webpack</title>
</head>
<body>
<div id="root"></div> <!-- Do not miss this one -->
</body>
</html>
Step 7: Install Webpack and Babel
Install Webpack, Babel and html-webpack-plugin as development dependencies.
npm install --save-dev webpack webpack-cli webpack-dev-server @babel/core @babel/preset-react @babel/preset-env babel-loader html-webpack-plugin
Or
If this looks verbose to you, you can do these in steps
npm install --save-dev webpack webpack-cli webpack-dev-server # webpack
npm install --save-dev @babel/core @babel/preset-react @babel/preset-env babel-loader #babel
npm install --save-dev html-webpack-plugin
Why babel? Read more: https://babeljs.io/docs/
In a nutshell, some of the reasons we use babel are:
-
JavaScript ECMAScript Compatibility:
- Babel allows developers to use the latest ECMAScript (ES) features in their code, even if the browser or Node.js environment doesn't support those features yet. This is achieved through the process of transpiling, where Babel converts modern JavaScript code (ES6 and beyond) into a version that is compatible with a wider range of browsers and environments.
-
JSX Transformation:
- JSX (JavaScript XML) is a syntax extension for JavaScript used with React. Babel is required to transform JSX syntax into plain JavaScript, as browsers do not understand JSX directly. This transformation is necessary for React components to be properly rendered in the browser.
-
Module System Transformation:
- Babel helps in transforming the module system used in JavaScript. It can convert code written using the ES6 module syntax (
import
andexport
) into the CommonJS or AMD syntax that browsers and older environments understand.
- Babel helps in transforming the module system used in JavaScript. It can convert code written using the ES6 module syntax (
-
Polyfilling:
- Babel can include polyfills for features that are not present in the target environment. This ensures that your application can use newer language features or APIs even if they are not supported natively.
-
Browser Compatibility:
- Different browsers have varying levels of support for JavaScript features. Babel helps address these compatibility issues by allowing developers to write code using the latest features and then automatically transforming it to a version that works across different browsers.
Why html-webpack-plugin? Read more: https://webpack.js.org/plugins/html-webpack-plugin/
The html-webpack-plugin
is a popular webpack plugin that simplifies the process of creating an HTML file to serve your bundled JavaScript files. It automatically injects the bundled script(s) into the HTML file, saving you from having to manually update the script tags every time your bundle changes. To put it in perspective, if you don’t have this plugin, you won’t see your react index file injected into the html file.
Step 8: Configure Babel
Create a .babelrc
file in the project root and add the following configuration:
// .babelrc
{
"presets": ["@babel/preset-react", "@babel/preset-env"]
}
Step 9: Configure Webpack
Create a webpack.config.js
file in the project root.
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
],
devServer: {
static: path.resolve(__dirname, 'public'),
port: 3000,
},
};
Step 10: Update package.json
scripts
Update the "scripts" section in your package.json
file.
"scripts": {
"start": "webpack serve --mode development --open",
"build": "webpack --mode production"
}
Note: Do not replace the contents of package.json here. Just update the scripts section
Step 11: This is where our hard work pays off
Now you can run your React project using the following command:
npm start
Visit http://localhost:3000
in your browser, and you should see your React app up and running.
This is it. This is a very basic version of our CRA. Stick around if you want to understand what we exactly did in the webpack.config.js
At this point our webpack config looks like this:
// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
],
devServer: {
static: path.resolve(__dirname, 'public'),
port: 3000,
},
};
Let's go through each section of the provided webpack.config.js
file and explain what each keyword means:
-
const path = require('path');
:- This line imports the Node.js
path
module, which provides utilities for working with file and directory paths. In our webpack configuration, it's used to ensure that file paths are specified correctly and consistently across different operating systems.
- This line imports the Node.js
-
const HtmlWebpackPlugin = require('html-webpack-plugin');
:- This line imports the
HtmlWebpackPlugin
module, which is a webpack plugin that simplifies the process of creating an HTML file to include the bundled JavaScript files. It's a convenient way to automatically generate an HTML file that includes the correct script tags for our React application.
- This line imports the
-
module.exports = { ... };
:- This line exports a JavaScript object, which contains the configuration for webpack. It specifies how webpack should bundle and process your code.
-
entry: './src/index.js',
:- This configuration tells webpack the entry point of your application, which is the main JavaScript file where the bundling process begins. In this case, it's
./src/index.js
.
- This configuration tells webpack the entry point of your application, which is the main JavaScript file where the bundling process begins. In this case, it's
-
output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', },
:- This configuration specifies where the bundled JavaScript file should be output.
path
is the directory, andfilename
is the name of the output file. In this case, it will be placed in thedist
directory with the namebundle.js
.
- This configuration specifies where the bundled JavaScript file should be output.
-
module: { rules: [ ... ], },
:- This section defines rules for how webpack should process different types of files. In this case, it specifies a rule for JavaScript and JSX files (those ending with
.js
or.jsx
). Thebabel-loader
is used to transpile these files using Babel, excluding files in thenode_modules
directory.
- This section defines rules for how webpack should process different types of files. In this case, it specifies a rule for JavaScript and JSX files (those ending with
-
plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', }), ],
:- This section includes an array of webpack plugins. In particular, it adds the
HtmlWebpackPlugin
, configured to use thepublic/index.html
file as a template. This plugin will automatically generate an HTML file with the correct script tags for the bundled JavaScript.
- This section includes an array of webpack plugins. In particular, it adds the
-
devServer: { static: path.resolve(__dirname, 'public'), port: 3000, },
:- This configuration is for the webpack development server. It specifies the base directory for serving static files (
public
in this case) and the port number (3000) on which the development server will run. The development server provides features like hot-reloading during development.
- This configuration is for the webpack development server. It specifies the base directory for serving static files (
And there you have it! We've just scratched the surface of the wild world of Webpack. But don't worry, this is just the opening act. Grab your gear, because in the upcoming articles, we're going to plunge into the deep end exploring the advanced terrains of Webpack. Stay tuned!
Top comments (0)