Build a webpack+react development environment from scratch

The environment mainly depends on the version

webpack installation and configuration

1. Getting started

Create a new project directory, initialize npm, and create a new development source directory

mkdir webpack-react && cd webpack-react
npm init -y
mkdir src

2.webpack-cli

Starting from version 4.x, webpack needs to be installed at the same time, webpack-cli (this tool is used to run webpack in the command line).

npm install webpack webpack-cli --save-dev

3.wepback configuration file

Create a new webpack.config.js file in the project root directory, which is the core file for running webpack.

webpack.config.js basic configuration

// webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',                           // 入口文件
    output: {                                             // webpack打包后出口文件
        filename: 'app.js',                             // 打包后js文件名称
        path: path.resolve(__dirname, 'dist')    // 打包后自动输出目录
    }
}

package.json file scripts configuration

"scripts": {
    "build": "webpack"
}

At this point, run npm run build on the command line to execute webpack. Webpack will automatically find the webpack.config.js file in the project root directory and execute the packaging.

npm run build
// webpack打包后的项目
├── dist
│   └── app.js             // 打包后的app.js
├── package.json
├── src
│   └── index.js           // 源目录入口文件
└── webpack.config.js

webpack.config.js module related configuration

webpack regards all files as modules. Static resources such as images, css files, and fonts will be packaged into js files, so loader files will be needed. More Loaders can query the URL . Next, we will install some necessary Loader files.

npm install style-loader css-loader url-loader --save-dev

webpack.config.js add module module

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	}
}

After importing the loader, you can import the css file or other static resources you want to import in your src/index.js file.

cd src && touch main.css

src/index.js file introduces css

import "./main.css";

webpack.config.js plugins configuration

After the main js files and static files can be successfully packaged into a js file, we need to put the js file into the html file. The webpack plugin ***html-webpack-plugin*** does this. It It can automatically generate an html file and put our packaged js file into html.

npm install html-webpack-plugin --save-dev

webpack.config.js configure plugins

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入插件

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({title: 'production'})		// 配置plugin
	]
};

After executing npm run build, we can see that there is an index.html file in the dist directory.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>name</title>
  </head>
  <body>
 // 打包后的app.js已经被自动插入了html文件
  <script type="text/javascript" src="app.js"></script></body>
</html>

At this point, the simplest and most basic requirements of webpack have been configured. At this point the project structure is:

├── dist                        // 生产目录
│   ├── app.js
│   └── index.html
├── package.json
├── src                        // 源目录
│   ├── index.js
│   └── main.css
└── webpack.config.js

React webpack configuration

install react

npm install react react-dom --save

Install react, wepback conversion dependencies

React components consist of JSX, which is not recognized by browsers and requires babel to convert.

  • babel-croe is the babel core file
  • babel-preset-env escapes ES6 to ES5
  • babel-preset-react escapes JSX to js
  • babel-loader webpack's babe transformation
npm install babel-core babel-preset-env babel-preset-react babel-loader --save-dev

.babelrc configuration file

Create a new .babelrc file in the project root directory. This file is the core configuration of bable, and babel will automatically recognize it in the project root directory.

// .babelrc
{
	"presets": ["env", "react"]
}

webpack babel-loader configuration

// 在webpack.config.js 的modules.rules中加入此配置
{
	test: /\.(js|jsx)$/,
	exclude: /node_modules/,
	use: {
		loader: 'babel-loader'
	}
}				    

html-webpack-plugin template configuration

We know that react needs to get a root element of the page, and then render will take effect. We can create a new html file and let the html-webpack-plugin plugin package items based on this file.

So we create a new html file in the root directory and use this file as a template.

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
        // react需要的渲染根元素
	<div id="root"></div>
</body>
</html>

At this point webpack.config.js configuration:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader'
				}
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({
			title: 'production',
			template: './index.html'    // 模板文件位置
		})		
	]
};

Write React, run webpack

// src/index.js
import React from 'react';
import ReactDom from 'react-dom';

import './main.css'

ReactDom.render(
	<h1>hello world</h1>,
	document.getElementById('root')
);

Run npm run build, generate the dist directory, open the index.html file in the dist directory, and you can find that the browser has rendered "hello world" normally.

dev environment hot update configuration

After the wepack of react is completed, do you find that every time you modify the code, if you want to see the effect, you have to repackage it once. The webpack-dev-server configuration can help us achieve hot updates and liberate our productivity in the development environment.

Install webpack-dev-server

npm install webpack-dev-server  --save-dev

webpack.config.js configuration

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'app.js',
		path: path.resolve(__dirname, 'dist')
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader'
				}
			},
			{
				test: /\.css$/,
				use: ['style-loader', 'css-loader']
			},
			{
				test: /\.(png|svg|jpg|gif)$/,
				use: ['url-loader']
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf)$/,
				use: ['url-loader']
			}
		]
	},
	plugins: [
		new HtmlWebpackPlugin({
			title: 'production',
			template: './index.html'    
		}),
		// hot 检测文件改动替换plugin
		new webpack.NamedModulesPlugin(),      
		new webpack.HotModuleReplacementPlugin()		
	],
       // webpack-dev-server 配置
	devServer: {
		contentBase: './dist',
		hot: true
	},
};

run webpack-dev-server

Add the scripts configuration to the package.json file:

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

Command line run npm run dev

You can enter localhost:8080 in the browser and the content is the index.html content in the dist directory. Modify the content or dependencies in src/index.js, that is, see it in the browser hot update in real time.

So far, the basic development environment of react webpack has been fully configured.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325890258&siteId=291194637