2.1 Write using create React APP
Create-react-app is facebook’s initial initialization project, designed for beginners to use for the first time without requiring a variety of configurations, and perfectly out of the box.
2.1.1 Project establishment
npx create-react-app my-app
cd my-app
npm start
Copy the code
The NPX command is a post-5.x enhancement of NPM that allows developers to temporarily download a project for execution and then automatically delete the temporarily downloaded project. Files are not generated in the global project.
The command above says, download the create-react-app project and run it to create a new project in the my-app directory.
2.1.2 Running the project
Once created, go to the my-app directory. Execute the NPM statement for a local development preview.
Enter the created folder my-app and run NPM run start to enter the local development preview.
As shown, we have run this program on local port 3000. Just open your browser and check it out.
2.2 Configuring WebPack programming manually
This chapter is a bit over the top, so if you’re interested, you can read it carefully. This section is for those of you who are interested in learning more, so if you don’t understand it right now, I suggest you review it later.
2.2.1 Project establishment
Let’s start by creating a Webpack-app folder. Then use VS Code to open the directory. Press Ctrl+~ to open the console. If the console cannot be opened, the hotkey is occupied. Click on the menu view -> Terminal.
The first step is to enter NPM init to create a configuration file for the front-end project.
Go straight back to the end.
2.2.2 Installing required development packages
Install react and react-dom packages
npm install --save-dev react react-dom
Copy the code
Install webpack
npm install --save-dev webpack-cli webpack webpack-dev-server
Copy the code
2.2.3 Write a React Hello World
First we’ll write a HelloWorld React component
import React, { PureComponent } from 'react'
export default class index extends PureComponent {
render() {
return (
<div>
Hello world React!
</div>)}}Copy the code
But this is just one component, and we need an HTML page to accommodate the React component.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Helloworld React</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Copy the code
At this point, React’s preparations are complete.
We need to write WebPack to package this project, and WebPack provides DevServer support for development. Let’s take a look at how this works.
We create a file called ‘webpack.config.js’ in the project root directory.
const path = require('path')
module.exports = {
mode:'development'.entry: './src/index.js'.context: __dirname,
target: 'web'.devServer: {
proxy: {},
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true.hot: true.noInfo: true.port: 3000}}Copy the code
After configuring the webpack.config.js file, we will add a new command to the scripts node in packageInfo.json.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server"
},
Copy the code
After we run NPM run dev on the terminal, you should see the following in the console.
Webpack compiles and tells us that it does not recognize the JSX format. The question then extends to how do we configure the modern front end.
For front-end code conversion, Babel translation is now commonly used. Let’s take a look at the plugins needed to compile React. Click here to see how Babel configures Webpack
- First, we need to install Babel and enter it on the terminal
npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react
- We have modified
webpack.config.js
The file. Make him look like this
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development'.entry: './src/entry.js'.context: __dirname,
target: 'web'.devServer: {
proxy: {},
contentBase: path.join(__dirname, 'public'),
port: 3000
},
module: {
rules: [{
test: /\.js$/.exclude: /node_modules/.loader: "babel-loader"}},plugins: [
new HtmlWebpackPlugin(
Object.assign({}, {
inject: true.template: __dirname + '/public/index.html',})),]}Copy the code
- Create it in the root directory
.bablerc
This file is used for configurationbabel
Compiled, enter the following in the file.
{
"presets": ["@babel/preset-env"."@babel/preset-react"]}Copy the code
- I don’t know if you noticed, but I modified the entry file. Since the React component doesn’t work properly, we need to tell the React framework which DOM to inject the component into. This file can configure global stores, routes, and Settings. We are in
src
Directory creationentry.js
, the following isentry.js
File source.
import React from 'react';
import ReactDOM from 'react-dom';
import Index from './index';
ReactDOM.render(<Index />, document.querySelector('#app'));
Copy the code
The code is very simple, just call ReactDOM to render the React component under the node id app.
OK, now we run NPM run dev again, you will see the webpack compiled successfully, we will now open the browser, type http://localhost:3000, you will see the webpack compiled successfully.
2.2.4 Adding HMR Support to WebPack (Hot Update)
Have you noticed that we need to refresh the whole page after the modification of this project? It doesn’t have that kind of high end, big dynamic refresh, right?
Now let’s add hot updates to our project.
We will make the following changes to the webpack.config.js file
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack')
module.exports = {
mode: 'development'.entry: [
'webpack/hot/dev-server'.'./src/entry.js'].output: {
filename: '[name].bundle.js'.path: path.resolve(__dirname, 'dist')},context: __dirname,
target: 'web'.devServer: {
proxy: {},
contentBase: path.join(__dirname, 'public'),
hot: true.port: 3000
},
module: {
rules: [{
test: /\.js$/.exclude: /node_modules/.loader: "babel-loader"}},plugins: [
new HtmlWebpackPlugin(
Object.assign({}, {
inject: true.template: __dirname + '/public/index.html',})),new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
}
Copy the code
Notice, we added NamedModulesPlugin and HotModuleReplacementPlugin two plug-ins. We also added hot: True to the devServer node and appended the Output node.
We then modify the entry.js file to look like this:
import React from 'react';
import ReactDOM from 'react-dom';
import Index from './index';
ReactDOM.render( < Index / > , document.querySelector('#app'));
if (module.hot) {
module.hot.accept()
}
Copy the code
We run the project again with NPM run dev, then modify the string in the index.js file, and you will see that the page content is now updated without a refresh.
2.2.5 WebPack optimizes packaging speed
Let’s add a new statement “webpack”:”webpack” to the scripts node of package.json and see what the project’s default packaging speed is now.
Time: 2211 ms
2.2.5.1 Babel cache
We modify the Babel configuration item in the webpack.config.js file
module: {
rules: [{
test: /\.js$/.exclude: /node_modules/.loader: "babel-loader? cacheDirectory=true"}},Copy the code
Add cacheDirectory=true to babel-loader and execute the compilation again. The first time you see that the speed is not optimized because the cache file is not created yet, but the second time the speed is increased by 20%.
Time: 1644 ms (500 ms)
Other strategies include extracting common components, adding hashes, etc. We’ll talk more about that later.
Download source address :github.com/yodfz/learn…
The original address: www.yodfz.com/detail/35/2…