📜 ⬆️ ⬇️

Using Babel and Webpack to set up a React project from scratch

There are many tools to prepare an environment for React-development. For example, in our materials on the React training course , the create-react-app tool is used, which allows you to create a template project that contains everything you need to develop React-applications. The author of the article, the translation of which we publish today, wants to talk about how to independently set up the environment for developing React-projects using Babel and Webpack. These tools are also used in projects created by the create-react-app tools, and we believe that anyone who studies React-development will be interested in getting to know them and the methodology for creating React-projects at a deeper level. Namely, it will discuss how to configure the Webpack so that this tool would use Babel to compile JSX code into JavaScript code, and how to configure the server used in developing React projects.



Webpack


Webpack is used to compile JavaScript modules. This tool is often called a “bandler” (from the bundler) or “module builder”. After installing it, you can work with it using the command line interface or its API . If you are not familiar with Webpack - it is recommended to read about the basic principles of its work and see its comparison with other assemblers of modules. This is how, at a high level, what Webpack does looks like.


Webpack job

Webpack takes everything the project depends on and converts it into static resources that can be passed to the client. Packaging applications is very important, as most browsers limit the ability to download resources at the same time. In addition, it allows you to save traffic, sending the client only what he needs. In particular, Webpack uses an internal cache, thanks to which modules are loaded onto the client only once, which, as a result, accelerates the loading of sites.

Babel


Babel is a transpiler that is mainly used to transform constructs adopted in newer versions of the ECMAScript standard into a form that can be understood by both modern and non-newer browsers and other environments in which JavaScript can run. Babel can also convert to JavaScript and JSX code using @ babel / preset-react .


Babel

Thanks to Babel, we can use JSX when developing React applications. For example, here is the code in which JSX is used:

import React from "react"; function App(){ return(  <div>     <b>Hello world!</b>  </div> ) } export default App; 

Such code looks neat, it is clear, it is easy to read and edit. Looking at it, you can immediately understand that it describes the component that returns the <div> element, which contains the text Hello world! in bold. And here is an example of code doing the same thing in which JSX is not used:

 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require("react"); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function App(props) { return _react2.default.createElement(   "div",   null,   _react2.default.createElement(     "b",     null,     "Hello world!"   ) ); } exports.default = App; 

The advantages of the first example over the second are obvious.

Prerequisites


In order to configure the React-application project, we need the following npm-modules.


Now, create a new project in the react-scratch folder using npm ( npm init ) and install some of the above packages with the following command:

 npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader css-loader webpack webpack-cli style-loader webpack-dev-server 

The entry point to the program will be the index.js file, which is contained in the src folder located in the root directory of the project. The structure of this project is shown below. Some files and folders are created automatically, you will need to create some yourself.


Project structure

A finished project that we will be dealing with here can be found in this repository.

The component folder will contain the project components (in our case there is only one component here). The dist folder, in the main.js file, will contain the compiled code, and index.html is, as already mentioned, the main HTML file of our application.

Webpack setup


Webpack can be customized in many ways. In particular, the settings of this tool can take the form of command line arguments or be present in the project as a configuration file called webpack.config.js . It is necessary to describe and export the object containing the settings. We will start setting up this file with a description of the object that looks like this (we will consider it in parts, and below we will give its full code):

 { entry: "./src/index.js", mode: "development", output: {   filename: "./main.js" }, } 

The entry property specifies the main file with the project source code. The value of the mode property indicates the type of environment to compile (in our case, the development environment is development ) and where to place the compiled file.

Project work


Place the following code in the index.html file of our project located in the dist folder:

 <!DOCTYPE html> <html lang="en" dir="ltr"> <head>   <meta charset="utf-8">   <title>React From Scratch</title> </head> <body>   <div id="root">   </div> </body> <script type="text/javascript" src="main.js"> </script> </html> 

Notice the script tag present in this file. It points to the main.js file, which will be obtained during the compilation of the project. We will use the <div> element with the root identifier to display the React application.

Now install the react and react-dom packages:

 npm install react react-dom 

We bring in the following code to index.js :

 import React, { Component } from "react"; import ReactDOM from "react-dom"; import App from "./component/app.component"; ReactDOM.render(<App />, document.querySelector("#root")); 

This is the standard code for similar React application files. Here we connect the libraries, connect the component file and output the application to the <div> with the root identifier.

Here is the code for the app.component.js file:

 import React, { Component } from "react"; import s from "./app.component.css"; class MyComponent extends Component { render() {   return <div className={s.intro}>Hello World</div>; } } export default MyComponent; 

Here is the code for the app.component.css file:

 .intro { background-color: yellow; } 

Babel setting


Babel is a powerful transpiler. In particular, he is able to convert LESS to CSS, JSX to JS, TypeScript to JS. We will use with it only two configurations - react and env (they are also called “presets”). Babel can be configured differently, in particular, we are talking about command line tools, a special settings file, a standard package.json file. We are satisfied with the last option. Add the following section to package.json :

 "babel": {   "presets": [     "@babel/env",     "@babel/react"   ] } 

With these settings, Babel will know which presets he needs to use. Now we’ll configure Webpack to use Babel.

Setting up a Webpack to work with Babel


Here we will use the babel-loader library, which will allow using Babel with a Webpack. In fact, it’s about Babel being able to intercept and process files before they are processed by Webpack.

▍JS files


Here are the rules for working with JS-files (this code will go to the file webpack.config.js ), they represent one of the properties of an object with settings exported by this file:

 module: {   rules: [     {       test: /\.m?js$/,       exclude: /(node_modules|bower_components)/,       use: {         loader: "babel-loader"       }     },   ] } 

The rules property of the object presented here contains an array of rules, according to which the file specified by the regular expression described in the test property should be processed. In this case, the rule will apply to all files with the .m and .js node_modules and we don’t want to node_modules files from the node_modules and bower_components folders. Further, here we indicate that we want to use the babel-loader. After that, our JS-files will be processed first by Babel tools, and then packed using Webpack.

▍CSS files


Add in the rules array of the module object the settings for processing CSS files:

 module: {   rules: [     {       test: /\.m?js$/,       exclude: /(node_modules|bower_components)/,       use: {         loader: "babel-loader"       }     },     {       test: /\.css$/,       use: [         "style-loader",         {           loader: "css-loader",           options: {             modules: true           }         }       ]     },  ] } 

The task of processing CSS files will be solved by means of style-loader and css-loader. The use property can accept an array of objects or strings. The loaders are called starting from the last, so our files will first be processed using the css-loader. We set up this tool by writing true modules property of the options object. Thanks to this, CSS styles will only be applied to the components into which they are imported. Css-loader will allow import commands in CSS files, after which the style-loader will add what you get, in the form of the style tag, in the <head> section of the page:

 <style> <-- ваш css --> </style> 

▍Static Resources


We will continue working on the module settings object, describing the rules for processing static resources:

 module: {   rules: [     {       test: /\.m?js$/,       exclude: /(node_modules|bower_components)/,       use: {         loader: "babel-loader"       }     },     {       test: /\.css$/,       use: [         "style-loader",         {           loader: "css-loader",           options: {             modules: true           }         }       ]     },     {       test: /\.(png|svg|jpg|gif)$/,       use: ["file-loader"]     }   ] } 

If the system encounters a file with a PNG, SVG, JPG or GIF extension, then a file loader will be used to process such a file. Processing such files is important for the proper preparation and optimization of the project.

Development Server Setup


Now, in the webpack.config.js file, webpack.config.js 's configure the development server:

 devServer: {   contentBase: path.join(__dirname, "dist"),   compress: true,   port: 9000,   watchContentBase: true,   progress: true }, 

The contentBase property of the contentBase settings devServer points to the folder where our resources are located and the index.html file. The port property allows you to specify the port that the server will listen on. The watchContentBase property allows watchContentBase to monitor the changes of files in the folder specified by the contentBase property.

Here is the complete code for the webpack.config.js file:

 const path = require("path"); module.exports = { entry: "./src/index.js", mode: "development", output: {   filename: "./main.js" }, devServer: {   contentBase: path.join(__dirname, "dist"),   compress: true,   port: 9000,   watchContentBase: true,   progress: true }, module: {   rules: [     {       test: /\.m?js$/,       exclude: /(node_modules|bower_components)/,       use: {         loader: "babel-loader"       }     },     {       test: /\.css$/,       use: [         "style-loader",         {           loader: "css-loader",           options: {             modules: true           }         }       ]     },     {       test: /\.(png|svg|jpg|gif)$/,       use: ["file-loader"]     }   ] } }; 

Now we add to the package.json , to the scripts section, the command to start the development server and the command to start the project build:

 "scripts": {   "dev": "webpack-dev-server",   "start": "webpack" }, 

Now everything is ready to start the development server with the following command:

 npm run dev 

If you now go to http: // localhost: 9000 , you will see the page of our project.


Project page in browser

To build a project, use the following command:

 npm run start 

After that, you can open the index.html file in the browser and see the same thing that could be seen by launching the development server and going to http: // localhost: 9000 .

Results


This article provides an overview of how Webpack and Babel are configured for use in React projects. In fact, on the basis that we have disassembled today, you can create much more complex configurations. For example, instead of CSS, you can use LESS, instead of the usual JS, write in TypeScript. If necessary, you can, for example, customize the minification of files and much more. Of course, if today your first acquaintance with the process of self-tuning React-projects took place, it may seem to you that all this is very difficult and much easier to use the ready-made template. However, once you understand this a bit, you will understand that a slight increase in the complexity of the settings gives you more freedom, allowing you to customize your projects exactly as you need it, not relying entirely on certain “standard” solutions and reducing your dependence on of them.

Dear readers! What approach do you most often use when preparing the working environment for React-projects?

Source: https://habr.com/ru/post/436886/