Perspective of front end engineering Part 2: basic introduction of webpack

Wei 1 2020-11-13 06:33:05
perspective end engineering basic introduction


1 Webpack Characteristics

 This is from the Internet
This is from the Internet

Webpack It's a powerful packaging tool . stay Webpack Everything in is modular .Webpack Official website Banner The picture illustrates this idea perfectly .Webpack Starting from an entry file, recursively analyze the module dependencies , Package these modules into one or more files based on dependencies .

At present, almost all the front-end construction and development adopt Webpack . because Webpack There is a strong community ecology , monthly Webpack More than a million downloads . adopt loader、plugin Support Webpack Integration with leading front-end frameworks and languages , such as Vue、React、TypeScript.

  • Support all modularity It can be done to ES6 modular 、commonjs modular 、AMD Modules and other standard modules are packaged .
  • code splitting You can type code into multiple chunk, Load on demand , It means our site doesn't have to wait for the whole js Only after the resource download is completed can we interact , Can greatly increase the speed .
  • Powerful and flexible plug-in system Webpack A lot of built-in plug-ins are available , Including its own architecture, plug-in system can meet all the packaging requirements .
  • loader With the help of loader Preprocessing is not js resources ,Webpack You can package all static resources .

2 Webpack Construction process

Webpack The construction process of is an event flow mechanism . The whole construction process can be seen as a pipeline , Each link is responsible for a single task , After processing, we will go to the next step .Webpack Events will be posted at each link , There are opportunities for built-in and custom plug-ins to intervene Webpack The building process of , control Webpack The result of building .Webpack The basic build flow chart of is as follows :

graph LR
A( initialization )-->B( Start compilation )
B( Start compilation )-->C( Compiler module )
C( Compiler module )-->D( Compile the complete )
D( Resource output )-->E( complete )
  • initialization Read webpack Configuration files and shell Parameters in the script , Initialize after merging parameters Webpack , Generate Compiler object .
  • Start compilation perform Compiler Of run Method to start compilation .
  • Compile the complete Start with the entry file , Call... In the configuration loader Compile the module , And sort out the dependency relationship between modules , Until all modules are compiled .
  • Resource output According to the dependency between the entry and the module , Assemble the contents compiled in the previous step into one by one chunk ( Code block ), And then put chunk Add to the list of resources waiting to be output .
  • complete After confirming the output resources , Configure according to the specified output path and file name , Write resources to the disk's file system , Complete the entire build process .

3 The core concept

entrance

The entrance is Webpack The starting point for building ,Webpack Start with the entry file during the build process , Compile modules recursively , And analyze the dependency relationship between modules , Finally, we get the dependency graph .Webpack The module is assembled according to the dependency diagram , Output to the final bundle In file .

We can do it in Webpack Configuration in the configuration file of entry attribute , To specify the entry file , The entry file can be one or more than one .

Let's take an example :

// Webpack .config.js
module.exports = {
entry: './src/app.js'
};

Scenarios where multiple portals are configured are common in multi page applications . If you configure multiple portals, you can do this :

// Webpack .config.js
module.exports = {
entry: {
pageOne: './src/pageOne/app.js',
pageTwo: './src/pageTwo/app.js'
}
};
Output

To configure output Options can indicate Webpack How to output 、 Where to output our static resource file .

Let's take an example of output How to use :

// Webpack .config.js
module.exports = {
output: {
filename: 'bundle.js',
path: './dist'
}
};

In the above example , We instruct Webpack The final output file name is bundle.js , The output directory is ./dist.

loader

loader Use

Webpack It can't deal with non itself js Resources , But we can be in Webpack Introduction in css、 picture 、 Font, etc js file . for example :

// app.js
import Styles from './styles.css';

that Webpack How to achieve it ?

Webpack Use in loader Right js File conversion .loader Can be in our import Or when loading modules , Preprocess files , Will not js File contents of , Finally, it's converted into js Code .

loader There are three ways to use it :

  • To configure stay Webpack .config.js The document specifies
  • inline At every import Specify... On the line of the statement
  • CLI stay shell The order specifies .

In practical applications , Most of them are used in configuration , On the one hand, in the configuration file , It's very intuitive to see what kind of files are used loader, On the other hand , In the case of complex projects , Easy to maintain .

Let's take a simple example of loader Use :

// Webpack .config.js
module.exports = {
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' }
]
}
};

We need to tell Webpack When you meet css When you file , Use css-loader Pre treatment . Here because css-loader It's alone npm modular , We need to install it before using it :

npm install --save-dev css-loader

frequently-used loader

Webpack You can handle anything that's not js Language , Thanks to the abundance of loader, Used in daily development loader, Can be found in the community . Here are some common loader Give a brief description of .

  • babel-loader take ES2015+ Translate the code into ES5.
  • ts-loader take TypeScript Translate the code into ES5.
  • css-loader analysis @import and url(), And the dependency of the reference is resolved .
  • style-loader stay HTML In the injection <style> The label will css Add to DOM in . Usually with css-loader Use a combination of .
  • sass-loader load sass/scss File and compile it into css.
  • postcss-loader Use PostCSS Load and translate CSS file .
  • html-loader take HTML Export to string .
  • vue-loader Load and translate Vue Components .
  • url-loader and file-loader equally , But if the file is less than the configured limit , Can return data URL.
  • file-loader Extract the file to the output directory , And return to the relative path .
plugin

Use of plug-ins

The plug-in is Webpack A very important function of ,Webpack It is also built on the plug-in system . The plug-in mechanism has been greatly enhanced Webpack The function of , by Webpack Increased enough flexibility . Through plug-ins , We can do it in Webpack In the process of building , Introduce your own operations , Intervention builds results .

Let's take a look at the use of plug-ins through an example :

// Webpack .config.js
const HtmlWebpack Plugin = require('html-Webpack -plugin');
const Webpack = require('Webpack ');
const config = {
plugins: [
new Webpack .optimize.UglifyJsPlugin(),
new HtmlWebpack Plugin({template: './src/index.html'})
]
};
module.exports = config;

Example , We used two plug-ins , One is built-in UglifyJsPlugin plug-in unit , The plug-in is for js Compress , Reduce the size of the file . One is an external plug-in HtmlWebpack Plugin, Used to automatically generate entry files , And inject the latest resources into HTML in .

Common plug-ins

  • HtmlWebpack Plugin Automatically generate the entry file , And inject the latest resources into HTML in .
  • CommonsChunkPlugin To create a separate file , It is often used to extract common modules from multiple modules .
  • DefinePlugin Used to define global constants to be used at compile time .
  • DllPlugin Split bundle Reduce unnecessary builds .
  • ExtractTextWebpack Plugin Change the text from bundle In a separate file . The common scene is from bundle Lieutenant general css Extract to independent css In file .
  • HotModuleReplacementPlugin Replace during operation 、 Add or remove modules , Without reloading the entire page .
  • UglifyjsWebpack Plugin Yes js Compress , Reduce the size of the file .
  • CopyWebpack Plugin Copy a single file or an entire directory to the build directory . A common scenario is to copy the static images of a project directly to the built directory without building it .

4 How to use Webpack

Let's take a look at a simple example Webpack Use . It is assumed that you have installed the latest version of nodejs and npm, Because the old version may encounter various problems .

4.1 install

establish Webpack -demo Catalog , initialization npm, And in Webpack -demo Install... In directory Webpack and Webpack -cli:

mkdir Webpack -demo && cd Webpack -demo
npm init -y
npm install Webpack Webpack -cli --save-dev

Webpack -cli Used to run on the command line Webpack . Local installation is recommended here Webpack and Webpack -cli, Because of global installation ,Webpack The upgrade will affect all projects .

Let's first add some directories and files to the project :

Webpack -demo
├── package.json
├── dist
├── index.html
└── src
└── index.js

index.html The contents are as follows :

<!doctype html>
<html>
<head>
<title>Webpack -demo</title>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>

src/index.js The contents are as follows :

function createEl() {
var element = document.createElement('div')
element.innerHTML = 'hello world'
return element;
}
document.body.appendChild(createEl());

4.2 First build

Run on the command line :

./node_modules/.bin/Webpack
Hash: 2353b0d3d427eaa8a18a
Version: Webpack 4.29.6
Time: 175ms
Built at: 2019-04-03 22:08:36
Asset Size Chunks Chunk Names
main.js 1 KiB 0 [emitted] main
Entrypoint main = main.js
[0] ./src/index.js 175 bytes {0} [built]

You can see , We didn't specify the packaged entry and output exit in the configuration file , There are no configuration parameters specified on the command line , But you can see in ./dist There is a new main.js. This is because Webpack Configuration in progress entry The default value is ./src, The default directory for exports is ./dist.

Webpack -demo
├── package.json
├── dist
| └── main.js
├── index.html
└── src
└── index.js

Added to the project directory after construction main.js.

<!doctype html>
<html>
<head>
<title>Webpack -demo</title>
</head>
<body>
<script src="./dist/main.js"></script>
</body>
</html>

We will now index.html The script reference in is modified to the built file ./dist/main.js, Preview in browser , If everything is OK, you should be able to see text output on the page hello world.

4.3 Use profile

For a simple build ,Webpack Basically, zero configuration can be achieved . But for complex single page applications , You need to use Webpack To provide personalized features .

First of all, we add a new item in the project root directory Webpack .config.js file :

// Webpack .config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

In the configuration file , adopt entry The entry file is specified as ./src/index.js, adopt output The specified output directory is ./dist, The output file name is bundle.js. The directory structure is updated as follows :

Webpack -demo
├── package.json
├── Webpack .config.js
├── index.html
├── dist
| └── bundle.js
└── src
└── index.js

At the same time, in order to call simply , We are package.json File to set the shortcut command to call ./node_modules/.bin/Webpack.

// package.json
{
"scripts": {
"build": "Webpack "
}
}

Execute the build command again :

npm run build
> Webpack -demo@1.0.0 build C:\work\tech\Webpack -demo
> Webpack
Hash: d0fa6b1e011af414e622
Version: Webpack 4.29.6
Time: 157ms
Built at: 2019-04-03 22:42:50
Asset Size Chunks Chunk Names
bundle.js 1 KiB 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/index.js 175 bytes {0} [built]

take index.html Medium script Change the reference link to ./dist/bundle.js, Preview the page in the browser , Text will be output if not unexpected hello world.

4.4 The use of plug-in

We found that in the process of building , If the name of the resource after construction has changed ,index.html References to resources in will be modified passively , Very inconvenient , We introduce HtmlWebpack Plugin To help us automatically generate the entry file , Automatically inject the generated resource file into index.html in .

install :

npm install --save-dev html-Webpack -plugin

To configure :

const path = require("path");
const HtmlWebpack Plugin = require("html-Webpack -plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
plugins: [new HtmlWebpack Plugin()]
};

In the configuration file , We introduce plug-ins , And in plugins In the options , Add the plug-in to the array after instantiation . The plug-in will automatically generate index.html, So... In the original catalog index.html Files can be deleted .

Webpack -demo
├── package.json
├── Webpack .config.js
├── dist
| └── bundle.js
└── src
└── index.js

Execute the build command again :

$ npm run build
> Webpack -demo@1.0.0 build C:\work\tech\Webpack -demo
> Webpack
Hash: 39dc7567ef99a69140e7
Version: Webpack 4.29.6
Time: 1241ms
Built at: 2019-04-03 22:53:44
Asset Size Chunks Chunk Names
bundle.js 1 KiB 0 [emitted] main
index.html 182 bytes [emitted]
Entrypoint main = bundle.js
[0] ./src/index.js 175 bytes {0} [built]

After the order was executed, we found out that our ./dist There's one more index.html file , also index.html Resource references in are automatically updated to <script type="text/javascript" src="bundle.js"></script>.

4.5 Use loader Handle css file

In order to make Webpack Can handle import Come in css file , We need to install and configure style-loader and css-loader.

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

modify Webpack The configuration is as follows :

const path = require("path");
const HtmlWebpack Plugin = require("html-Webpack -plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
plugins: [new HtmlWebpack Plugin()]
};

In this way , When Webpack Match to suffix .css All of your files will use css-loader and style-loader To deal with .

And then we have ./src Add a style file in the directory main.css. In the pattern , Set the font color of the text to red .

// main.css
div{color: red}

And then we were in ./src/index.js I quote main.css:

import "./main.css";
function createEl() {
var element = document.createElement("div");
element.innerHTML = "hello world";
return element;
}
document.body.appendChild(createEl());

Execute the build command :

$ npm run build
> Webpack -demo@1.0.0 build C:\work\tech\Webpack -demo
> Webpack
Hash: f9fcb8cfd689f4b96ce6
Version: Webpack 4.29.6
Time: 2672ms
Built at: 2019-04-03 23:24:40
Asset Size Chunks Chunk Names
bundle.js 6.85 KiB 0 [emitted] main
index.html 182 bytes [emitted]
Entrypoint main = bundle.js
[0] ./src/index.js 199 bytes {0} [built]
[1] ./src/main.css 1.05 KiB {0} [built]
[2] ./node_modules/css-loader/dist/cjs.js!./src/main.css 170 bytes {0} [built]
+ 3 hidden modules

Preview in browser , Not surprisingly, the color of the font has turned red , Open browser debugging tool , You can see in the <head> There's a... In the tag <style> label .

<style type="text/css">
div {
color: red;
}
</style>

Through the above complete example , We demonstrated Webpack How to use several configurations at the core of , We are right. Webpack There should be a basic understanding of the use of .

Webpack There are many other useful configuration items in , The reason for the length of the article is not detailed . You can check it Official documents Configure and practice by yourself .

summary

In this section, we Webpack A general introduction is given . With the help of loader、Webpack Can handle all resources ,JS Of 、 Not JS Of , Fine . Through plug-ins , We can do it in Webpack Each event node in the construction process adds its own behavior , To influence Webpack The construction of . Yes Webpack We have realized the use of , It can provide a basis for us to build the basic framework of the project .

The author has a front-end engineering practical course just launched ——《 Perspective front end Engineering 》.

Click to learn about 《 Perspective front end Engineering 》.

With Vue For example , Combined with the author's engineering practice in the team , Lead you to build a scaffold from scratch , Dismantle the technical points used in scaffold construction one by one , I hope you'll see , Everyone has a deep understanding of scaffolding and engineering ideas .

The course catalog

Opening words : What is front-end engineering

The first part : Formwork design

The first 01 course : Template function design
The first 02 course :Webpack Basic introduction
The first 03 course : Build project template framework
The first 04 course : Front end modular solutions
The first 05 course : Building local development environment
The first 06 course : Build local Mock service
The first 07 course : Introduce code checking tools
The first 08 course : Automatically generate sprite map
The first 09 course : Build from the browser
The first 10 course : Build on the environment
The first 11 course : Integrated mobile debugging tools
The first 12 course : Introduce unit testing
The first 13 course : introduce e2e test
The first 14 course :Webpack Build performance optimization
The first 15 course : Add deployment capabilities
The first 16 course : Aggregate project configuration and template

The second part : Command line design

The first 17 course :cli Functional design ( On )
The first 18 course :cli Functional design ( Next )

Conclusion : An open mind is a higher level of engineering

I believe that after finishing this course , We have at least the following gains :

  • Have a systematic understanding of front end engineering ;
  • Can independently design a set of front-end engineering solutions ;
  • The breadth of knowledge has been greatly improved ;
  • Into a better platform , Get better pay .

interested , I hope you will support me a lot !


Author's brief introduction :

Wang Chao , Now fast Dog Taxi ( primary 58 Express ) Head of front end .

I have worked in Renren 、 qihoo 360,8 Years of working experience in the Internet .

from 0 To 1 Set up a fastdog front-end team , Responsible for the construction of team technical system , In the order Webpack and Vue Based on 、 Node.js The middle layer is complementary , automation 、 engineering 、 Component based fastdog front end technology system .

版权声明
本文为[Wei 1]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple