• United States+1
  • United Kingdom+44
  • Afghanistan (‫افغانستان‬‎)+93
  • Albania (Shqipëri)+355
  • Algeria (‫الجزائر‬‎)+213
  • American Samoa+1684
  • Andorra+376
  • Angola+244
  • Anguilla+1264
  • Antigua and Barbuda+1268
  • Argentina+54
  • Armenia (Հայաստան)+374
  • Aruba+297
  • Australia+61
  • Austria (Österreich)+43
  • Azerbaijan (Azərbaycan)+994
  • Bahamas+1242
  • Bahrain (‫البحرين‬‎)+973
  • Bangladesh (বাংলাদেশ)+880
  • Barbados+1246
  • Belarus (Беларусь)+375
  • Belgium (België)+32
  • Belize+501
  • Benin (Bénin)+229
  • Bermuda+1441
  • Bhutan (འབྲུག)+975
  • Bolivia+591
  • Bosnia and Herzegovina (Босна и Херцеговина)+387
  • Botswana+267
  • Brazil (Brasil)+55
  • British Indian Ocean Territory+246
  • British Virgin Islands+1284
  • Brunei+673
  • Bulgaria (България)+359
  • Burkina Faso+226
  • Burundi (Uburundi)+257
  • Cambodia (កម្ពុជា)+855
  • Cameroon (Cameroun)+237
  • Canada+1
  • Cape Verde (Kabu Verdi)+238
  • Caribbean Netherlands+599
  • Cayman Islands+1345
  • Central African Republic (République centrafricaine)+236
  • Chad (Tchad)+235
  • Chile+56
  • China (中国)+86
  • Christmas Island+61
  • Cocos (Keeling) Islands+61
  • Colombia+57
  • Comoros (‫جزر القمر‬‎)+269
  • Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)+243
  • Congo (Republic) (Congo-Brazzaville)+242
  • Cook Islands+682
  • Costa Rica+506
  • Côte d’Ivoire+225
  • Croatia (Hrvatska)+385
  • Cuba+53
  • Curaçao+599
  • Cyprus (Κύπρος)+357
  • Czech Republic (Česká republika)+420
  • Denmark (Danmark)+45
  • Djibouti+253
  • Dominica+1767
  • Dominican Republic (República Dominicana)+1
  • Ecuador+593
  • Egypt (‫مصر‬‎)+20
  • El Salvador+503
  • Equatorial Guinea (Guinea Ecuatorial)+240
  • Eritrea+291
  • Estonia (Eesti)+372
  • Ethiopia+251
  • Falkland Islands (Islas Malvinas)+500
  • Faroe Islands (Føroyar)+298
  • Fiji+679
  • Finland (Suomi)+358
  • France+33
  • French Guiana (Guyane française)+594
  • French Polynesia (Polynésie française)+689
  • Gabon+241
  • Gambia+220
  • Georgia (საქართველო)+995
  • Germany (Deutschland)+49
  • Ghana (Gaana)+233
  • Gibraltar+350
  • Greece (Ελλάδα)+30
  • Greenland (Kalaallit Nunaat)+299
  • Grenada+1473
  • Guadeloupe+590
  • Guam+1671
  • Guatemala+502
  • Guernsey+44
  • Guinea (Guinée)+224
  • Guinea-Bissau (Guiné Bissau)+245
  • Guyana+592
  • Haiti+509
  • Honduras+504
  • Hong Kong (香港)+852
  • Hungary (Magyarország)+36
  • Iceland (Ísland)+354
  • India (भारत)+91
  • Indonesia+62
  • Iran (‫ایران‬‎)+98
  • Iraq (‫العراق‬‎)+964
  • Ireland+353
  • Isle of Man+44
  • Israel (‫ישראל‬‎)+972
  • Italy (Italia)+39
  • Jamaica+1876
  • Japan (日本)+81
  • Jersey+44
  • Jordan (‫الأردن‬‎)+962
  • Kazakhstan (Казахстан)+7
  • Kenya+254
  • Kiribati+686
  • Kosovo+383
  • Kuwait (‫الكويت‬‎)+965
  • Kyrgyzstan (Кыргызстан)+996
  • Laos (ລາວ)+856
  • Latvia (Latvija)+371
  • Lebanon (‫لبنان‬‎)+961
  • Lesotho+266
  • Liberia+231
  • Libya (‫ليبيا‬‎)+218
  • Liechtenstein+423
  • Lithuania (Lietuva)+370
  • Luxembourg+352
  • Macau (澳門)+853
  • Macedonia (FYROM) (Македонија)+389
  • Madagascar (Madagasikara)+261
  • Malawi+265
  • Malaysia+60
  • Maldives+960
  • Mali+223
  • Malta+356
  • Marshall Islands+692
  • Martinique+596
  • Mauritania (‫موريتانيا‬‎)+222
  • Mauritius (Moris)+230
  • Mayotte+262
  • Mexico (México)+52
  • Micronesia+691
  • Moldova (Republica Moldova)+373
  • Monaco+377
  • Mongolia (Монгол)+976
  • Montenegro (Crna Gora)+382
  • Montserrat+1664
  • Morocco (‫المغرب‬‎)+212
  • Mozambique (Moçambique)+258
  • Myanmar (Burma) (မြန်မာ)+95
  • Namibia (Namibië)+264
  • Nauru+674
  • Nepal (नेपाल)+977
  • Netherlands (Nederland)+31
  • New Caledonia (Nouvelle-Calédonie)+687
  • New Zealand+64
  • Nicaragua+505
  • Niger (Nijar)+227
  • Nigeria+234
  • Niue+683
  • Norfolk Island+672
  • North Korea (조선 민주주의 인민 공화국)+850
  • Northern Mariana Islands+1670
  • Norway (Norge)+47
  • Oman (‫عُمان‬‎)+968
  • Pakistan (‫پاکستان‬‎)+92
  • Palau+680
  • Palestine (‫فلسطين‬‎)+970
  • Panama (Panamá)+507
  • Papua New Guinea+675
  • Paraguay+595
  • Peru (Perú)+51
  • Philippines+63
  • Poland (Polska)+48
  • Portugal+351
  • Puerto Rico+1
  • Qatar (‫قطر‬‎)+974
  • Réunion (La Réunion)+262
  • Romania (România)+40
  • Russia (Россия)+7
  • Rwanda+250
  • Saint Barthélemy (Saint-Barthélemy)+590
  • Saint Helena+290
  • Saint Kitts and Nevis+1869
  • Saint Lucia+1758
  • Saint Martin (Saint-Martin (partie française))+590
  • Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)+508
  • Saint Vincent and the Grenadines+1784
  • Samoa+685
  • San Marino+378
  • São Tomé and Príncipe (São Tomé e Príncipe)+239
  • Saudi Arabia (‫المملكة العربية السعودية‬‎)+966
  • Senegal (Sénégal)+221
  • Serbia (Србија)+381
  • Seychelles+248
  • Sierra Leone+232
  • Singapore+65
  • Sint Maarten+1721
  • Slovakia (Slovensko)+421
  • Slovenia (Slovenija)+386
  • Solomon Islands+677
  • Somalia (Soomaaliya)+252
  • South Africa+27
  • South Korea (대한민국)+82
  • South Sudan (‫جنوب السودان‬‎)+211
  • Spain (España)+34
  • Sri Lanka (ශ්‍රී ලංකාව)+94
  • Sudan (‫السودان‬‎)+249
  • Suriname+597
  • Svalbard and Jan Mayen+47
  • Swaziland+268
  • Sweden (Sverige)+46
  • Switzerland (Schweiz)+41
  • Syria (‫سوريا‬‎)+963
  • Taiwan (台灣)+886
  • Tajikistan+992
  • Tanzania+255
  • Thailand (ไทย)+66
  • Timor-Leste+670
  • Togo+228
  • Tokelau+690
  • Tonga+676
  • Trinidad and Tobago+1868
  • Tunisia (‫تونس‬‎)+216
  • Turkey (Türkiye)+90
  • Turkmenistan+993
  • Turks and Caicos Islands+1649
  • Tuvalu+688
  • U.S. Virgin Islands+1340
  • Uganda+256
  • Ukraine (Україна)+380
  • United Arab Emirates (‫الإمارات العربية المتحدة‬‎)+971
  • United Kingdom+44
  • United States+1
  • Uruguay+598
  • Uzbekistan (Oʻzbekiston)+998
  • Vanuatu+678
  • Vatican City (Città del Vaticano)+39
  • Venezuela+58
  • Vietnam (Việt Nam)+84
  • Wallis and Futuna+681
  • Western Sahara (‫الصحراء الغربية‬‎)+212
  • Yemen (‫اليمن‬‎)+967
  • Zambia+260
  • Zimbabwe+263
  • Åland Islands+358
Thanks! We'll be in touch in the next 12 hours
Oops! Something went wrong while submitting the form.

Exploring Marvels of Webpack : Ep 1 - React Project without CRA

Chetan Oli

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?

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, allowing 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.

That's all well and good, but why do we need to learn about manual configuration? At some point in your career, you'll likely have to adjust webpack configurations. And if that’s not a convincing reason, how about satisfying your curiosity? 🙂

Let’s begin our journey.

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 in one of our files. In a large application, it’s not usually possible to write everything in a single file, so we have multiple modules piled up together.

bundler:It is a tool (which is webpack in our case), that bundles up everything we have used in our project and converts it 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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .js hosted with ❤ by GitHub

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'));
view raw .js hosted with ❤ by GitHub

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>
view raw .html hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

Why babel? Read more: https://babeljs.io/docs/

In a nutshell, some of the reasons we use Babel are:

  1. 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 yet support them. 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.
  2. 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.
  3. Module System Transformation:
    • Babel helps in transforming the module system used in JavaScript. It can convert code written using the ES6 module syntax (import and export) into the CommonJS or AMD syntax that browsers and older environments understand.
  4. Polyfilling:
    • Babel can include polyfills for features not present in the target environment. This ensures your application can use newer language features or APIs even if they are not supported natively.
  5. 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"]
}
view raw .json hosted with ❤ by GitHub

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,
},
};
view raw .js hosted with ❤ by GitHub

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"
}
view raw .json hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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.

There’s more

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,
},
};
view raw .js hosted with ❤ by GitHub

Let's go through each section of the provided webpack.config.js file and explain what each keyword means:

  1. const path = require('path');
    • This line imports the Node.js path module, which provides utilities for working with file and directory paths. Our webpack configuration ensures that file paths are specified correctly and consistently across different operating systems.
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
    • This line imports the HtmlWebpackPlugin module. This webpack plugin simplifies the process of creating an HTML file to include the bundled JavaScript files. It's a convenient way of automatically generating an HTML file that includes the correct script tags for our React application.
  3. module.exports = { ... };
    • This line exports a JavaScript object, which contains the configuration for webpack. It specifies how webpack should bundle and process your code.
  4. 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.
  5. output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', },
    • This configuration specifies where the bundled JavaScript file should be output: path is the directory, and filename is the name of the output file. In this case, it will be placed in the dist directory with the name bundle.js.
  6. 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). The babel-loader is used to transpile these files using Babel, excluding files in the node_modules directory.
  7. plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', }), ],
    • This section includes an array of webpack plugins. In particular, it adds the HtmlWebpackPlugin, configured to use the public/index.html file as a template. This plugin will automatically generate an HTML file with the correct script tags for the bundled JavaScript.
  8. 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.

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!

Get the latest engineering blogs delivered straight to your inbox.
No spam. Only expert insights.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings

You may also like

No items found.

Exploring Marvels of Webpack : Ep 1 - React Project without CRA

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?

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, allowing 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.

That's all well and good, but why do we need to learn about manual configuration? At some point in your career, you'll likely have to adjust webpack configurations. And if that’s not a convincing reason, how about satisfying your curiosity? 🙂

Let’s begin our journey.

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 in one of our files. In a large application, it’s not usually possible to write everything in a single file, so we have multiple modules piled up together.

bundler:It is a tool (which is webpack in our case), that bundles up everything we have used in our project and converts it 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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .js hosted with ❤ by GitHub

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'));
view raw .js hosted with ❤ by GitHub

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>
view raw .html hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

Why babel? Read more: https://babeljs.io/docs/

In a nutshell, some of the reasons we use Babel are:

  1. 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 yet support them. 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.
  2. 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.
  3. Module System Transformation:
    • Babel helps in transforming the module system used in JavaScript. It can convert code written using the ES6 module syntax (import and export) into the CommonJS or AMD syntax that browsers and older environments understand.
  4. Polyfilling:
    • Babel can include polyfills for features not present in the target environment. This ensures your application can use newer language features or APIs even if they are not supported natively.
  5. 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"]
}
view raw .json hosted with ❤ by GitHub

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,
},
};
view raw .js hosted with ❤ by GitHub

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"
}
view raw .json hosted with ❤ by GitHub

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
view raw .sh hosted with ❤ by GitHub

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.

There’s more

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,
},
};
view raw .js hosted with ❤ by GitHub

Let's go through each section of the provided webpack.config.js file and explain what each keyword means:

  1. const path = require('path');
    • This line imports the Node.js path module, which provides utilities for working with file and directory paths. Our webpack configuration ensures that file paths are specified correctly and consistently across different operating systems.
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
    • This line imports the HtmlWebpackPlugin module. This webpack plugin simplifies the process of creating an HTML file to include the bundled JavaScript files. It's a convenient way of automatically generating an HTML file that includes the correct script tags for our React application.
  3. module.exports = { ... };
    • This line exports a JavaScript object, which contains the configuration for webpack. It specifies how webpack should bundle and process your code.
  4. 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.
  5. output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', },
    • This configuration specifies where the bundled JavaScript file should be output: path is the directory, and filename is the name of the output file. In this case, it will be placed in the dist directory with the name bundle.js.
  6. 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). The babel-loader is used to transpile these files using Babel, excluding files in the node_modules directory.
  7. plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', }), ],
    • This section includes an array of webpack plugins. In particular, it adds the HtmlWebpackPlugin, configured to use the public/index.html file as a template. This plugin will automatically generate an HTML file with the correct script tags for the bundled JavaScript.
  8. 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.

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!

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings