preface

The React + WebPack4 Front-end construction project is divided into three chapters. The link is below. The purpose is to build a React backend management system from scratch

React + WebPack4 Build front-end projects (1) Build infrastructure projects

React + WebPack4 设 置 Front-End project

React + WebPack4 Build front-end project (3) Package optimization

Webpack configuration tutorial

React + webPack4.x build front-end project (4) Configure extraction and differentiation environment

React + WebPackage 4.x build front-end project (5) Configure multiple pages

React + WebPack4. x Multi-module package configuration

This is chapter one, basic project construction

This article focuses on step-by-step constructionreactProject prototype (not usedcreate-react-app.umiEtc.), including configuring basic Webpack, and then toreact+webpackConfiguration integration, to complete the project startup and packaging (not includedreactThe use of related technology stacks andwebpackPackage optimization). I’ll cover these in more detail in a future postreactRelated technology stack (family bucketreact+react-router+axios+antd+mobx) as well aswebpackPackaging optimization

React, Webpack has some foundation

Technology stack

  • The react framework:

React +react-router+axios+ ANTd +mobx

  • Pack to build

webpack4.x

Without further ado, high energy ahead, here we go

Initialize the project

Webpack installation (WebPack demo)
  1. Create package.json, execute NPM init and press Enter all the way

  2. Install webPack basic package (this article uses WebPack 4.x, attention, everyone)

      npm install --D webpack webpack-dev-server webpack-cli
    Copy the code

    Webpack 4.x must have Webapck – CLI installed as a note

Create a new SRC /index.js file and add the following code

console.log("hello world")
Copy the code

Add “build”:”webpack” to the package.json script

(dist/main.js) (SRC /index.js) (dist/main.js) (SRC /index.js) (dist/main.js) (SRC /index.js) (webpack4.x)

Webpack can successfully build packaged JS files in this project, please check the official documentation for other uses!

Below starts the official configuration webpack ~

Step by step from the most basic configuration, to create a different environment Webpack configuration file to distinguish different environments, in the detailed configuration of different environments webpack; Finally, configure the React development and packaging environment

Basic configuration for WebPack

Create webpack.config.js in the build directory

The basic configuration

const path = require("path"); Function resolve(dir) {return path.resolve(__dirname, dir)} module.exports = {// specify build environment mode:"development", // output: {path: resolve(".. /dist"), filename: "js/[name].[hash].js", publicPath: }, // module module:{}, // plugins:[], // devServer: {}}Copy the code

Each configuration above has a note, what do you not understand the basic configuration can see the official document

2. Prepare and configure HTML templates, implement THE packaging of HTML templates and install plug-ins

npm install -D html-webpack-plugin
Copy the code

To create the index.html template in the root directory, the code is simple

<! DOCTYPE HTML > < HTML > <head> <meta charset=" utF-8 "> <meta name="viewport" content="width=device-width,initial-scale=1.0">  <title>mydemo</title> </head> <body> <div id="app"></div> <! -- built files will be auto injected --> </body> </html>Copy the code

3. Add plugins to webpack.config.js

new HtmlWebpackPlugin({ filename: resolve('./.. /dist/index.html'), // HTML template generation path template: 'index.html',// HTML template inject: True, // true: default, the script tag is at the bottom of the body of the HTML file hash: true, // Inserting HTML into the packaged resource will add the hash // HTML file to compress minify: {removeComments: CollapseWhitespace: true, // Collapse attributequotes: For example, <p id="test" /> output <p id=test/>}})Copy the code

4, modify package.json build command to build package “build” for specified configuration file: “Webpack –config build/webpack.config.js”, then run NPM run build again, at which point you can insert the HTML template and the packaged resources into the HTML template, and then pack into the dist directory

Extract the WebPack configuration file

Js, webpack.base.config.js, webpack.dev.config.js, and webpack.dev. webpack.prod.config.js

To extract the WebPack configuration, use the WebPack-merge plug-in

npm install -D webpack-merge
Copy the code

This plugin is used to merge WebPack configurations from different files into one complete WebPack configuration. See below for details

Utils.js is the utility method used for webpack configuration

const path = require("path")

exports.resolve = function (dir) {
    return path.resolve(__dirname, dir)
}

Copy the code

Webpack.base.config.js is a common configuration of Webpack in different environments

// module. Exports = {// entry: {app: "./ SRC /index"}, // export: {path: // path: // path: // path: // path: // path: // path: // path: // path: // path: // path: // path: utils.resolve(".. / dist "), the filename: "js / [name] [hash] js", publicPath: "/" / / resources access path prefix} after packaging, / / module module: {},}Copy the code

Webpack.dev.config.js is the configuration of the project development environment

const webpackMerge = require("webpack-merge"); const baseWebpackConfig = require("./webpack.base.config") const utils = require("./utils") const HtmlWebpackPlugin = Require ("html-webpack-plugin") module.exports = webpackconfig (baseWebpackConfig,{// specify build environment mode:"development", // plugins:[new HtmlWebpackPlugin({filename: utils.resolve('./../dist/index.html')), // 'index.html',// HTML template inject: true, // true: default, script tag is located at the bottom of the BODY of the HTML file})], // Development environment locally started service configuration devServer: {}});Copy the code

Webpack.prod.config. js is the configuration of the project production environment

const webpackMerge = require("webpack-merge"); const baseWebpackConfig = require("./webpack.base.config") const utils = require("./utils") const HtmlWebpackPlugin = Module. Exports = webpackconfig () {// specify the build environment mode:"production", // plugins:[new HtmlWebpackPlugin({filename: utils.resolve('./../dist/index.html')), // 'index.html',// HTML template inject: true, // true: default value, the script tag is located at the bottom of the body of the HTML file hash: Minify: {removeComments: true, // collapseWhitespace: True, // compress whitespace removeAttributeQuotes: true // removeAttributeQuotes}})],})Copy the code

Before modifying the package.json build command:

"build": "webpack --config build/webpack.prod.config.js"
Copy the code

Then run NPM run build again and everything is fine!

Configure the production environment webpack.dev.config.js. The steps above are already complete, but it is still relatively easy

Configure the development environment webpack.dev.config.js

The development environment requires us to use the Webpack-dev-server plug-in, which has been installed above

1, add package.json command and start the service with webpack-dev-server

"dev": "webpack-dev-server",
Copy the code

By executing NPM run dev, a service can now be started normally on port 8080. The root of the service is the root of the project

However, this mode does not specify the configuration file to start, so you need to specify the configuration file to start

 "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.config.js",
Copy the code

On the next run of NPM run dev, you will see that the configured resources and HTML templates have been built by Webpack

When the browser opens http://localhost:8080, the SRC /index.js content is executed

2, Enrich the webpack-dev-server configuration, add the development environment startup service configuration under the devServer property of webpack.dev.config.js

// devServer: {historyApiFallback: true, // Index.html file is loaded by default when the path is not found. False, // tell the server where to supply the content. Compress: true, // All services are gzip compressed: port: "8081", // specify a valid segment publicPath: "/", // access resources with prefix proxy: {// interface request proxy},}Copy the code

NPM run dev to start the service. At this time, the service port has been changed to 8081 in the configuration file. Enter http://localhost:8081 to modify SRC /index.js

Webpack-dev-server detailed configuration

Introducing the React framework

The installationreact
npm install -S react react-dom
Copy the code

Modify SRC/index. The js file, use the react, react – dom to react spa is inserted into the HTML page template of the box id for the app to run the project NPM run dev, no accident you surprised to see an error. This is because WebPack is not ready to compile the code that builds React

Support for react packaged builds (webpack configuration)

We all know that to compile react code using WebPack and build it into browser-ready code, you need to use tools like Babel to “translate” it.

1, Install and configure Babel (babel7.x)

npm install -D @babel/core @babel/preset-env @babel/preset-react 
npm install -D @babel/plugin-transform-runtime @babel/runtime @babel/runtime-corejs2
Copy the code
  • @babel/core babelThe core library of Babel
  • @babel/preset-envConvert ES6, ES7 syntax to ES5. Versions of bebel7 and above use this single default package for syntax conversions and are deprecatedPreset -stage-0, preset-stage-1, preset-stage-2Wait for the bags. However, this package does not yet transform ES6, and some of es7’s new features includeArray.includes(), which requires us to use@babel/plugin-transform-runtimethe
  • @babel/preset-react Convert react syntax to ES5
  • @babel/plugin-transform-runtimeSupport for some new ES6, ES7 syntax

Now that the installation is complete, we need to add the configuration of Babel, create.babelrc in the project directory, and configure it as follows

{ "presets": [ ["@babel/preset-env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] } }], "@babel/preset-react" ], "plugins": [ ["@babel/plugin-transform-runtime",{ "corejs": 2, // polyfill needs @babel/runtime-corejs2 "useBuildIns":"usage", // to reduce the size of the package}]]}Copy the code

“Corejs “: 2, “useBuildIns”:”usage” : 2,” Babel “:”usage” : 2, “useBuildIns”:”usage”

  • "corejs": 2: @babel/runtime + @babel/plugin-transform-runtime = @babel/runtime + @babel/plugin-transform-runtime = @babel/runtime Use @babel/ Runtime-corejs2.
  • "useBuildIns":"usage": To implement true on-demand import, which is what new features are packaged with, use the experimental useBuildIns:” Usage “.

2. Webpack4. x configures and compiles packaging rules

Install the loaders

  • babel-loaderCompile projects using Babel
npm install -D babel-loader
Copy the code
  • Style - loader, CSS - loaderCompiling CSS files
npm install -D style-loader css-loader
Copy the code
  • url-loader file-loaderImporting file paths (images, fonts)
npm install -D url-loader file-loader
Copy the code
  • less-loaderidentifylessfile
npm install -D less less-loader
Copy the code

After installing these packages, we need to add package build rules to webpacl.base.config.js and add the rules property under Module

Rules: [{test: / \. (js | JSX) $/, / / a matching loaders the file extension of the regular expression processing, here used to match the js and JSX files (must) provides: /node_modules/,// Mask unnecessary files (folder) (Optional) loader: 'babel-loader',// Loader name (mandatory)}, {test: /\.css$/, use:[{loader: 'style - loader', / / create the < style > < / style >}, {loader: 'CSS - loader, / / convert the CSS}}, {test: / \. Less $/, use: [{loader: 'style - loader,}, {loader:' CSS - loader,}, {loader: 'less - loader, / / compile less - > CSS},],}, {test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, // url-loader contains file-loader. File-loader is not used. Images smaller than 10000B are imported from Base64, and images larger than 10000B are imported from path name: 'static/img/[name].[hash:7].[ext]' } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: Name: 'static/fonts/[name].[hash:7].[ext]'}}]Copy the code

These configurations have fewer compile-build configurations for VUE files than for the VUE framework. You will find in the Vue project vue-loader, vue-style-loader, vue-template-compiler these three plug-ins are essential, which are used to process the Vue file package

Continue adding in webpack.base.config.js

Resolve: {extensions: ['.js', '.json'], // Resolve the extension. Alias: {'@': path.join(__dirname, '.. ') alias: {'@': path.join(__dirname, '.. ', "SRC ") // Use the @ symbol instead of the SRC path in the project to import the file path more easily}}Copy the code

3. Write pages, run projects, test packages

Create an assets/img directory and place the pictures in it

SRC create home/index.js, home/test. CSS, home/test.less home/index.js

import React from 'react'
import "./test.less"
import "./test.css"
import buyImg from "@/assets/img/icon_buy_task.png"
import testImg from "@/assets/img/bg_store.png"
export default class Home extends React.Component {
    render(){
        return (
            <div className="test test2">
                <p>hello world</p>
                <img src={buyImg} alt="" />
                <img src={testImg} alt="" style={{width:360,height:60}}/>
            </div>
        )
    }
}
Copy the code

test.css

.test2 {
    font-size: 32px;
}
Copy the code

test.less

.test {
    background: rebeccapurple;
}
Copy the code

Then modify the SRC /index.js entry file

import React from 'react'
import ReactDom from 'react-dom'
import HomePage from "./home"
class App extends React.Component {
    render(){
        return (
            <div style={{color:"#333"}} className="test test2">
                <HomePage />
            </div>
        )
    }
}
ReactDom.render(<App/>,document.getElementById("app"))
Copy the code

At this point, the basic prototype of the project has been formed:

Then we run and package the project to execute firstnpm run devThe service starts normally and the browser is openedhttp://localhost:8081Page effect:

NPM run build is executed. The package succeeds

At this point, the larger images and the JS bundle are packaged properly, so how do we test the packaged code? Here I recommend a plug-in (which can run without deploying static packages to the Nginx server) http-server

npm install -g http-server
Copy the code

Install the http-server package globally. After the installation is successful, go to CD dist and run the http-server command

A service is started at this time and port 8080 is enabled by default

The diagram below:

At this time open the browser, enter http://localhost:8081, found the page is normal!

So there is a basic project prototype!

Use the React stack with WebPack4 to build a front-end project

I recommend

Get coupons every day, shopping price comparison, self-use or promotion can earn commission; Every day, you can get taxi vouchers, gas vouchers, Ele. me takeout vouchers, fruit and vegetable vouchers, Meituan takeout vouchers, flash purchase vouchers, preferred vouchers, hotel vouchers, etc. After receiving and successfully using vouchers, you can get rebate commission.

Click here for detailsClick the linkOr wechat scan below the small program code