This is a great tutorial for beginners.



Directory:

  1. The knowledge you will learn
  2. Establishing the project
  3. Configuration webpack
  4. Configure the Babel
  5. Writing the React component
  6. HTML webpack plugin
  7. webpack dev server
  8. conclusion


The knowledge you will learn

  • How do I install and configure WebPack
  • How do I install and configure Babel
  • Install React
  • How to write the React component
  • How do I introduce packaged files into an HTML page
  • How do I install and configure WebPack Dev Server


Establishing the project

First, create the project directory:

mkdir webpack-react-tutorial && cd The $_Copy the code

The basic directory structure for creating the project:

mkdir -p srcCopy the code

Initialization project:

npm init -yCopy the code


Configuration webpack

Webpack is a very powerful tool. Learn webPack not only for building React projects, but for any front-end project.

Webpack extracts the original React component and is used to generate JavaScript code that (almost) every browser can understand.

Install webpack:

npm i webpack --save-devCopy the code

Also need to install webpack- CLI:

npm i webpack-cli --save-devCopy the code

Next, add the webpack command to package.json:

"scripts": {
    "build": "webpack --mode production"
}Copy the code

Now you don’t need to define configuration files for WebPack.

Older versions of WebPack didn’t automatically look up configuration files, but starting with Webpack 4, you can develop directly without a configuration file.

Next, I’ll install and configure Babel to compile our code.


Configure the Babel

The React component is mostly written in ES6 syntax. ES6 is a nice improvement over the syntax, but older browsers often can’t parse the new ES6 syntax. The stateful React component is instantiated as a class, so in order for ES6 to run in older browsers, we need to make some kind of transformation. We turn this conversion into compilation.

Webpack doesn’t know how to convert ES6 syntax to ES5, but Webpack can do it using a Loader. That is, the WebPack loader takes something as input and converts it to something else as output.

Babel-loader in WebPack takes the job of translating ES6 syntax into a syntax that browsers can understand.

  1. Babel Preset Env is responsible for the conversion of ES6 syntax to ES5
  2. Babel Preset React is responsible for converting JSX syntax to JavaScript

Install dependencies:

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react --save-devCopy the code

Don’t forget to configure Babel. Create the. Babelrc file in the project root directory as follows:

{
  "presets": ["@babel/preset-env"."@babel/preset-react"]}Copy the code

Now we need to write a short WebPack configuration file.

Create the webpack.config.js file as follows:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"}}]}};Copy the code

For each file with a JS or JSX extension, Webpack manages the code through babel-Loader to convert ES6 to ES5.

With this, we can write the React component.


Writing the React component

First, create two React components according to the Container/Presentation principle.

The container component is the component that holds all the logic: the function to handle state changes, the internal component state, and so on. Instead, the presentation component is just for presentation. The presentation component is a normal JavaScript function that receives data as props from the container component.

Next, I’ll build a simple React form with a text box.

Install React before writing the code:

npm i react react-dom --save-devCopy the code

Next, create a directory structure for the component:

mkdir -p src/js/components/{container,presentational}Copy the code

Let’s create a container component that meets the following criteria:

  • Have your own state
  • The rendering is an HTML form

Create a component:

touch src/js/components/container/FormContainer.jsxCopy the code

The code is as follows:

import React, { Component } from "react";
import ReactDOM from "react-dom";

class FormContainer extends Component {
  constructor() {
    super();

    this.state = {
      title: ""
    };
  }

  render() {
    return (
      <form id="article-form"> </form> ); }}export default FormContainer;Copy the code

This component does not currently do any work; it is just a framework for containing child components.

Create the child component below:

touch src/js/components/presentational/Input.jsxCopy the code

Our presentation component is a text box. An HTML text box has the following properties:

  • type
  • class
  • id
  • value
  • required

All of these attributes should be passed from the parent container component to the child component.

If input has its own state, be careful when using it to ensure that the HTML input is a controlled React component.

Install the following dependencies:

npm i prop-types --save-devCopy the code

Back to the React component, show the component code as follows:

import React from "react";
import PropTypes from "prop-types";

const Input = ({ label, text, type, id, value, handleChange }) => (
  <div className="form-group">
    <label htmlFor={label}>{text}</label>
    <input
      type= {type}
      className="form-control"
      id={id}
      value={value}
      onChange={handleChange}
      required
    />
  </div>
);

Input.propTypes = {
  label: PropTypes.string.isRequired,
  text: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  handleChange: PropTypes.func.isRequired
};

export default Input;Copy the code

Next, we include the presentation component with the container component:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import Input from ".. /presentational/Input.jsx";

class FormContainer extends Component {
  constructor() {
    super();

    this.state = {
      seo_title: ""
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({ [event.target.id]: event.target.value });
  }

  render() {
    const { seo_title } = this.state;
    return (
      <form id="article-form">
        <Input
          text="SEO title"
          label="seo_title"
          type="text"
          id="seo_title"value={seo_title} handleChange={this.handleChange} /> </form> ); }}export default FormContainer;Copy the code

The default entry file for Webpack is./ SRC /index.js. We create this file and import the container component FormContainer in the entry file

import FormContainer from "./js/components/container/FormContainer.jsx";Copy the code

We can then execute the following command to package:

npm run buildCopy the code

The packed JS file is in. /dist/main.js

Now let’s implement the packaging file into the HTML page.


HTML webpack plugin

To make React Form visible, we have to have WebPack create an HTML page and import the packaged JS file into the HTML.

Webpacks requires two additional components to handle HTML: html-webpack-plugin and html-loader.

Install dependencies:

npm i html-webpack-plugin html-loader --save-devCopy the code

Update the WebPack configuration file:

const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
  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"}})];Copy the code

Create a./ SRC /index.html file

<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" >
    <title>How to set up React, Webpack, and Babel</title>
</head>

<body>
    <div class="container">
        <div class="row mt-5">
            <div class="col-md-4 offset-md-1">
                <p>Create a new article</p>
                <div id="create-article-form"> <! -- form --> </div> </div> </div> </div> </body> </html>Copy the code

Finally, attach the React component to the element with id create-article-form:

const wrapper = document.getElementById("create-article-form");
wrapper ? ReactDOM.render(<FormContainer />, wrapper) : false;Copy the code

Once again the build:

npm run buildCopy the code

Look in the dist directory and you’ll see the HTML result file

With Webpack, instead of manually importing JS files into HTML, the packaged files will be injected automatically.

Open./dist/index.html and you’ll see the React form you just wrote in your browser


Webpack dev server

If you don’t want to run NPM run build every time you change a file to see the results, you can start the local development server using a simple three-line configuration. When configured, WebPack launches the application in the browser. In addition, the Webpack server automatically refreshes the browser window every time you save the file after a change.

Install dependencies:

npm i webpack-dev-server --save-devCopy the code

Update package. Json:

"scripts": {
  "start": "webpack-dev-server --open --mode development"."build": "webpack --mode production"
}Copy the code

Run the command:

npm startCopy the code

You should see the following screen in your browser:



Also, webPack Dev Server automatically refreshes the page every time the file is updated.


conclusion

Create-react-app is a way to start the React project, almost everything out of the box. But sooner or later, you’ll want to tweak or modify your old WebPack configuration.

If you learn how to configure React, Webpack, and Babel manually, you can configure the React project from scratch to suit your needs.

This knowledge is also useful for situations where you don’t need a full SPA but still want to build and distribute ES6 code. By combining WebPack and Babel, you can transform a bunch of React components into bundles suitable for distribution.


The original link: https://www.valentinog.com/blog/react-webpack-babel/