[Tutorial] Webpack development environment to build React detailed steps

1. Install Node.js

WebpackIs actually Node.jswritten, so the first installation Node.jsenvironment. And Node.jsthe integrated NPMpackage management, we use many modules behind the need to use NPMdownload.

First enter Node.js official website , select the corresponding system to download the installation package, for windowsusers directly download the installation package can be installed, if the Macosuser is recommended brew for installation. Node.jsThere are many versions, including the stable version and the development version, different projects need Node.jsdifferent versions, it is recommended that you install 8.xor later.

2. Install Webpack

Where we need to create a project, create a new folder, for example, I will create a C drive called myappthe folder (Only do presentations, put the system disk is not recommended at), It myappis the root directory of the current project.
In the address bar project root directly input cmdand press enter, can be opened in this directory command prompt, as shown below:
Here Insert Picture Description
In the command line input command, generating a custom package.jsonfile is used to describe items stored information is performed the following command:

cnpm init -y

Note: This tutorial consistent use Taobao mirror cnpmcommand to install, check before you use this command if the command to install cnpm

Enter the following command to install, install webpack to local project:

cnpm install --save-dev webpack 
#或者简写
cnpm i -D webpack

After a successful installation will myappautomatically generate the following under the project node_modulesdirectory and package.jsonfile:
Here Insert Picture Description
and then install webpack-clithe tool, execute the following command:

cnpm i -D webpack-cli

After the command is completed, we need package.jsonto configure packaged command file. In package.jsonthe file scripts, add the following configuration item properties:

{
    "scripts": {
        "build": "webpack --mode production"
    }
}

3. Installation react and react-dom

In the command prompt, locate the root directory of the current project, in turn execute the following command:
install react:

cnpm i -S react

Installation react-dom:

cnpm i -S react-dom

Installation babel:

cnpm i babel-loader @babel/core @babel/preset-env -D

Installation babel preset-react:

cnpm i @babel/preset-react -D

4. Create a project directory structure of the source file

Created in the project webpack.config.jsconfiguration file, and add in the configuration file JSXsyntax Babelcompiler support, document reads as follows:

module.exports = {
    resolve: {
        extensions: ['.wasm', '.mjs', '.js', '.json', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/, // jsx/js文件的正则
                exclude: /node_modules/, // 排除 node_modules 文件夹
                use: {
                    // loader 是 babel
                    loader: 'babel-loader',
                    options: {
                        // babel 转义的配置选项
                        babelrc: false,
                        presets: [
                            // 添加 preset-react
                            require.resolve('@babel/preset-react'),
                            [require.resolve('@babel/preset-env'), {modules: false}]
                        ],
                        cacheDirectory: true
                    }
                }
            }
        ]
    }
};

Were created in the project root directory srcand publicfolder structure of the project at this time has become in effect the following picture:
Here Insert Picture Description

src directory: source project used to store files, such as documents or .jsx .js file;
public directory: static file used to store items, such as .html files or pictures

Created in the public directory: index.html file (the default home page of the project);
created in the src directory: index.js, App.js file (write the source code);

public/index.htmlThe project file is the default home page, which reads as follows:

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <title>Hello React</title>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>

src/App.jsFile is a custom component, as follows:

import React from 'react';

function App () {
	return (
		<div>
			React from Webpack
		</div>
	);
};
export default App;

src/index.jsThe project file is a file entry, as follows:

import React from 'react';
import ReactDom from 'react-dom';
import App from './App';

ReactDom.render(<App />,document.getElementById('root'));

This, the directory structure of our project to build complete.
Then that we created these files, do some configuration. First open the webpack.config.jsfile, the configuration webpackof the entrance, add the following:

module.exports = {
    entry: './src/index.js',  //添加入口配置项
    // ...
};

In the following install html-webpack-pluginthis plug-in, execute the following command:

cnpm i html-webpack-plugin -D

The plug-in has two main functions:

  1. Introduction of external resources such as an html file script, link dynamically added after each hash compile, to prevent the external reference file cache problems;
  2. Create html file entry may be generated, such as single html page may generate a file entry, the configuration of the N html-webpack-plugin may generate N pages inlet.

After installation, and then modify webpack.config.jsthe configuration, introduced webpackthe use of plug-in:

const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
    // ...
    plugins: [
        new HtmlWebPackPlugin({
            template: 'public/index.html',
            filename: 'index.html',
            inject: true
        })
    ]
};

After the above operations are complete, you can perform package command:

npm run build

If the following content appears on the command line, proved successful package:
Here Insert Picture Description
After a successful package, the root directory of the project will generate a distfolder, the folder is stored in packaged .htmland .jsfiles.

5. Configure the local server

We can be based on Node.jsa Expressset up a local server, through Expressmiddleware webpack-dev-middlewareto implement and Webpackinteraction. Implement local service requires the following three steps:

Step 1: Install webpack-dev-server module
installation command:

cnpm i webpack-dev-server -D

Step Two: Configure service entry
After successful installation, you need to webpack.config.jsconfigure the settings of the file server:

const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
    mode: 'development',
    devtool: 'cheap-module-source-map',
    devServer: {
        contentBase: path.join(__dirname, './public/'),
        publicPath: '/',
        host: '127.0.0.1',
        port: 3000,
        stats: {
            colors: true
        }
    },
    //......
};

Step 3: Set the startup command
in package.jsonthe file scriptsproperties, add startstartup items:

{
    "scripts": {
        "build": "webpack --mode production",
        "start": "webpack-dev-server --mode development --open"
    }
}

After completion of the above steps, execute the command line npm startyou can start the server!
After the server is started, it will automatically open a browser and visit our configured Address:
Here Insert Picture Description
When the source code is modified, you can automatically refresh the page.
Here Insert Picture Description
This, React environment to build successful, we can develop projects in this environment, based on the.

to sum up

Due Webpackmainly for building and packaging items, and even some students at work simply out of reach Webpack, or project configuration only once Webpack, it will not be used again later. For these students, I hope this tutorial can bring some new stock of knowledge to you in the future when used, can have ideas and methods of operation.
There students will say, are now using scaffolding tools, directly create-react-appbuilt environment is good, convenient and easy. First of all, this view is correct, I also recommend that you use the tools to build a scaffold environment, but as a front-end engineer, we only know the operating principle of the environment, in order to better control the frame, when the code error, and will not a loss.
WebpackNot only is the premise of the front frame of the study, the students also will ask future interview, written examination compulsory, will work with content, with the development of front-end engineering, Webpackis becoming increasingly important, especially for large tier Internet companies, will It will not Webpackeven be able to directly determine whether you can be hired. So we learn Webpackis the first step into the front-end development work.

Published 124 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/p445098355/article/details/104517094