preface
Recently, I have been learning webpack basic use, project optimization and other issues. I always feel like I need to write something down. If you are interested in webpack, you can follow this article to try to build it.
I. Project construction
Initialize the project
mkdir react-webpack-demo
cd react-webpack-demo
npm init -y
Copy the code
Install Webpack, Webpack4 separates Webpack-CLI from Webpack, so install webpack webpack-CLI at the same time
npm i webpack webpack-cli -D
Copy the code
Webpack is recommended to be installed locally. If it is installed globally, the webpack version will be locked. Using WebPack for multiple projects will cause the project build failure due to version problems
Add run commands to package.json
"scripts": {
"dev": "webpack"
}
Copy the code
Next create the SRC file and SRC /index.js as the entry file under the project (SRC /index.js is the entry entry in the default webpack configuration)
Execute NPM run dev to see that a dist directory is generated under the project (packaged successfully)
So far a WebPack project has been set up, so let’s start configuring webPack and setting up a React project
Second, the loader
First create webpack.config.js under the project, which will use the properties in the default configuration instead of showing them all. Readers are invited to identify by attribute.
/**** webpack.config.js ***/
Webpack is configured by default
const path = require('path');
module.exports = {
/ / project entry file support STR | | [] {}
entry: path.resolve(__dirname, './src/index.js'),
// Project export
output: {
path: path.resolve(__dirname, './dist'),
filename: 'mian.js'
},
// The default packaging environment is production
// If it is a development environment, change it to Development
// Next, to see the packaged file, use development
mode: 'development'.These options determine how different types of modules in a project are handled.
module: {},
/ / the plugin
plugins: [],
// Whether to enable source-map
devtool: 'cheap-module-eval-source-map'
}
Copy the code
Webpack only supports JS/JSON by default. Loader can be used to preprocess files. This allows you to package any static resources other than JavaScript. You can easily write your own loader using Node.js.
Install style – loader/CSS – loader/file – loader
npm i css-loader style-loader file-loader -D
Copy the code
// webpack.config.js
module: {
rules: [{test: /\.css$/.use: [{loader: 'style-loader' },
{
loader: 'css-loader'.options: {
modules: true}},]}, {test: /\.(png|jpg|gif)$/.use: [{loader: 'file-loader'.options: {},},],}},Copy the code
Ok Now you can pack CSS files and image resources as you like.
So far everything is working fine, we’re trying to write some code in the entry file
const arr = [new Promise((a)= >{}),new Promise((a)= >{})]; arr.map(item= > {
console.log(item);
})
Copy the code
Review the files after you pack them
We want the effect to be able to convert ES5 code for browser compatibility, OK open whole.
Babel is used here for code conversion
/ / installation
npm i babel-loader @babel/core @babel/preset-env -D
// used in webpack.config.js
module: {
rules: [{test: /\.js/.loader: 'babel-loader'}},Copy the code
Create a.babelrc file in the root directory to match the configuration items of babel-loader
// .babelrc
{
"presets": ["@babel/preset-env"]}Copy the code
Run package NPM run dev
So far half the job is done, and the latest features, such as Promise, have yet to be transformed.
Go ahead and install @babel/ Polyfill and introduce it in the entry file
/ / installation
npm i @babel/polyfill -D
// index.js
import '@babel/polyfill';
Copy the code
OK now the compilation is successful and the generated code has all been successfully converted to ES5 code, but
Obviously just a few k code, now directly more than 400 K. The reason is that Webpack directly packaged all the methods in Polyfill into DIST, but I only used Promise, which was obviously not what I wanted.
This is where useBuiltIns needs to be configured
// Re-change the.babelrc file
{
"presets": [["@babel/preset-env",
{
// Describe the environment that you support/target for the project
"targets": {
"browsers": ["1%" >."last 2 versions"]},"corejs": 2.// The new version needs to specify the core library version
/ / "usage" | | "entry" false, the default is false
"useBuiltIns": "usage" // Inject as needed}}]]Copy the code
So far webpack based function basic end use of Babel, for more loader please refer to the www.webpackjs.com/loaders/
Third, the plugins
Let’s start with a wave of official descriptions
Webpack has a rich plugin interface. Most of the functionality of WebPack itself uses this plug-in interface. This plug-in interface makes WebPack extremely flexible.Copy the code
The previous step only implemented the functionality of packing CSS/JS/image resources. Now we will use the plug-in to automatically generate HTML files. Basic functions such as automatically empties dist directory every deployment
First, install the plugins the old-fashioned way
npm i html-webpack-plugin clean-webpack-plugin -D
Copy the code
To be used in a project, first create the index.html template under the project
const htmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
plugins: [
// Copy an HTML and import the last packaged resource into the HTML
new htmlWebpackPlugin({
// The page title needs to be used with EJS
title: "The test title".// HTML template path
template: "./index.html".// Output the file name
filename: "index.html".minify: {
// Compress HTML files
removeComments: true.// Remove comments from HTML
collapseWhitespace: true.// Remove whitespace and newline characters
minifyCSS: true // Compress inline CSS}}),// Clear the dist directory every time you deploy
new CleanWebpackPlugin()
],
Copy the code
Start building the React project
Install react React -dom first
npm i react react-dom -S
Copy the code
SRC to create the react.js file
import React, { Component } from 'react';
import ReactDom from 'react-dom';
class App extends Component {
render() {
return <div>
hello word`12
</div>}}// Add a div tag to index.html with id set to 'app'
ReactDom.render(<App />, document.getElementById('app'));
Copy the code
Modify the webpack. Config. Js
entry: path.resolve(__dirname, './src/react.js'),
output: {
path: path.resolve(__dirname, './dist'),
// Take the first 8 bits of the module identifier hash
filename: 'main_[hash:8].js'
},
Copy the code
There is an error when performing the react package. Webpack does not know the react syntax
Install @ Babel/preset – react
npm i @babel/preset-react -D
Copy the code
Configure @babel/preset- React in. Babelrc
{
"presets": [["@babel/preset-env", {// describe the environment that you support/target for the project"targets": {
"browsers": ["1%" >."last 2 versions"]},"corejs": 2, // The new version needs to specify the core library version"useBuiltIns": "usage"// inject as needed}],"@babel/preset-react"]}Copy the code
The React project should now be packaged properly. However, in daily development, we do not see the effect every time we finish the package. In this case, we need to create a service and the configuration of hot update.
First we need to install webpack-dev-server
npm i webpack-dev-server -D
Copy the code
Configure the webpack.config.js file
const webpack = require('webpack')
module.exports = {
// devServer and Entry are level
devServer: {
// points to the packaged file address
contentBase: './dist'.// Whether to open a new window automatically
open: true./ / the port number
port: 8081.// Whether to enable hot update
hot: true.// Enable hot module replacement instead of page refresh as backup in case of build failure.
hotOnly: true
},
plugins: [
// Enable hMR-hot Module Replacement
new webpack.HotModuleReplacementPlugin()
]
}
Copy the code
Add a command to package.json
"scripts": {
"server": "webpack-dev-server"
}
Copy the code
Now that a base version of React has been built, the next post will show you how to optimize your project using WebPack. Git address github.com/shanyq1673/…
React: WebPack builds from 0