search
HomeWeb Front-endJS TutorialDetailed explanation of the use of webpack v4

This time I will bring you a detailed explanation of the use of webpack v4, what are the precautions when using webpack v4, the following is a practical case, let's take a look.

Overview

This month ushered in the release of the official version of v4. This article is used to learn new features and summarize the must-use plugins & loaders for development, from dev to prd. You~

Big changes

Environment

Node.js 4 is no longer supported. Source Code was upgraded to a higher ecmascript version.

Usage

You have to choose (mode or --mode) between two modes now: production or development

mode is introduced in this new version Configuration items, developers can choose between none, development (development) and production (product) three modes. This configuration item uses production mode by default.

  1. The development mode gives you the ultimate development experience, including browser debugging related tools, extremely fast incremental compilation, and rich and comprehensive error information...

  2. The production mode includes a lot of release optimization, code compression, smooth runtime optimization, elimination of development-related code, ease of use, etc.

  3. none No Using the default is equivalent to the original state of all self-configurations in the old version.

#eg:

webpack --mode development

Usage

  1. Some Plugin options are now validated

  2. CLI has been move to webpack-cli, you need to install webpack-cli to use the CLI

  3. The ProgressPlugin (--progress) now displays plugin names

  4. At least for plugins migrated to the new plugin system

In the new version, the webpack command line tool is split into a separate warehouse, so additional installation of webpack is required- cli.

npm init -y //初始化项目
npm install webpack webpack-cli -D //安装webpack webpack-cli 依赖
npx webpack --mode development // npx可以直接运行node_modules/.bin目录下面的命令

Or configure the script build of package.json

"scripts": {
 "build": "webpack --mode development",
},

Load loader method summary

use

module: {
 rules:[
  { 
   test: /\.css$/,
   use: ['style-loader','css-loader']
  }
 ]
}

css-loader is used to parse and process the url path in the CSS file, and turn the CSS file into a module

Multiple loaders are required in order, written from right to left, because when converting It is converted from right to left

This plug-in first uses css-loader to process the css file, and then uses style-loader to turn the CSS file into a style tag and insert it into the head

loader

module: {
 rules:[
  {
   test: /\.css$/,
   loader: ["style-loader", "css-loader"]
  },
 ]
}

use loader

module: {
 rules:[
  {
   test: /\.css$/,
   use:[
    { loader:"style-loader"},
    { 
     loader: 'css-loader',
     options: {sourceMap: true}
    }
   ]
  }
 ]
}

These three ways of writing loaders have the same final packaging results

The options configuration item in the loader can be followed by "?" after the loader

eg:

{ 
 test: /\.jpeg$/, 
 use: 'url-loader?limit=1024&name=[path][name].[ext]&outputPath=img/&publicPath=output/', 
}

is the abbreviation of the following configuration

{ 
 test: /\.jpeg$/, 
 use: {
  loader:'url-loader',
  options:{
   limit:1024,
   name:[path][name].[ext],
   outputPath:img/
   publicPath:output/'
  }
 }
}

Develop necessary loader&plugins

  1. css-loader

  2. babel-loader

Talk about converting ES6 code to ES5

{
 test: /\.js/,
 use: {
  loader: 'babel-loader',
  query: {
   presets: ["env", "stage-0", "react"]
  }
 }
},

babel-loader's preset can be added to the query , you can also add a .babelrc file in the project root directory

.babelrc
{
 "presets": [
  "env",
  "stage-0",
  "react"
 ]
}

html-webpack-plugin

The basic function of the plug-in is to generate html files. The principle is very simple:

Insert the relevant entry thunk of the entry configuration in webpack and the css style extracted by extract-text-webpack-plugin into the template provided by the plug-in or the content specified by the templateContent configuration item to generate an html file, the specific insertion method is to insert the style link into the head element and the script into the head or body.

const HtmlWebpackPlugin = require('html-webpack-plugin');
new HtmlWebpackPlugin({
 template: './src/index.html',//指定产的HTML模板
 filename: `index.html`,//产出的HTML文件名
 title: 'index',
 hash: true,// 会在引入的js里加入查询字符串避免缓存,
 minify: {
  removeAttributeQuotes: true
 }
}),

You can use cnpm search html-webpack-plugin to find the usage of loader

less-loader sass-loader

Optimize towards prd

Extract public css code

它会将所有的入口 chunk(entry chunks)中引用的 *.css,移动到独立分离的 CSS 文件。因此,你的样式将不再内嵌到 JS bundle 中,而是会放到一个单独的 CSS 文件(即 styles.css)当中。 如果你的样式文件大小较大,这会做更快提前加载,因为 CSS bundle 会跟 JS bundle 并行加载。

npm i extract-text-webpack-plugin@next -D
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
let cssExtract = new ExtractTextWebpackPlugin({
 filename: 'css/css.css',
 allChunks: true
});
module:{
 rules:[
  {
   test: /\.css$/,//转换文件的匹配正则
   loader: cssExtract.extract({
    use: ["css-loader?minimize"]
   })
  },
 ]
}
plugins:[
 ...... ,
 + cssExtract
]

尽量减少文件解析,用resolve配置文件解析路径,include

rules: {
 test: /\.js$/,
 loader:'babel-loader',
 include: path.resolve(dirname, 'src'),//只转换或者编译src 目录 下的文件
 exclude: /node_modules/ //不要解析node_modules
}

resolve.mainFields

WebpackTest
|
|
| - src
| | - index.js
|
| - lib
| | - fetch
|  |
|  browser.js
|  node.js
|  package.json
|
| - webpack.config.js

当从 npm 包中导入模块时(例如,引入lib下的库),此选项将决定在 package.json 中使用哪个字段导入模块。根据 webpack 配置中指定的 target 不同,默认值也会有所不同。

package.json

lib文件夹下的package.json中配置相对应模块的key

{
 "name": "fetch",
 "version": "1.0.0",
 "description": "",
 "node": "./node.js",
 "browser": "./browser.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "keywords": [],
 "author": "",
 "license": "ISC"
}

webpack.config.js

在resolve解析对象中,加入lib的路径

resolve: {
 extensions: ['.js', '.json'],
 mainFields: ['main', 'browser', 'node'],
 modules: [path.resolve('node_modules'), path.resolve('lib')]
}

index.js

这样在index.js中引用第三方库时,会去查找modules下的路径中是否配置了所需的文件,知道在package.json中找到mainFields中的key对应文件,停止。

let fetch = require('fetch');
console.log(fetch);

打包后 console.log出的对象

如果交换mainFields中的key顺序

mainFields: ['main', 'node','browser']

打包后 console.log出的对象,因为找到了key=node对应的文件就停止了查找

DllReferencePlugin

这个插件是在 webpack 主配置文件中设置的, 这个插件把只有 dll 的 bundle(们)(dll-only-bundle(s)) 引用到需要的预编译的依赖。

新建webpack.react.config.js

const path = require('path');
const webpack = require('webpack')
module.exports = {
 entry: {
  react: ['react', 'react-dom']
 },
 output: {
  path: path.join(dirname, 'dist'),// 输出动态连接库的文件名称
  filename: '[name]_dll.js',
  library: '_dll_[name]'//全局变量的名字,其它会从此变量上获取到里面的模块
 },
 // manifest 表示一个描述文件
 plugins: [
  new webpack.DllPlugin({
   name: '_dll_[name]',
   path: path.join(dirname, 'dist', 'manifest.json')//最后打包出来的文件目录和名字
  })
 ]
}

在entry入口写入要打包成dll的文件,这里把体积较大的react和react-dom打包

output中的关键是library的全局变量名,下文详细说明dll&manifest工作原理

打包dll文件

webpack --config webpack.react.config.js --mode development

打包出来的manifest.json节选

打包出来的react_dll.js节选

可见manifest.json中的 name值就是

output:{
  library:_dll_react
}

manifest.json就是借书证,_dll_react就像图书馆书籍的条形码,为我们最终找到filename为react_dll.js的参考书

使用“参考书”

在webpack.config.js中加入“借书证”

new webpack.DllReferencePlugin({
  manifest: path.join(dirname, 'dist', 'manifest.json')
})

再运行

webpack --mode development

打包速度显著变快

打包后的main.js中,react,react-dom.js也打包进来了,成功~

import React from 'react';\n//import ReactDOM from 'react-dom';
 (function(module, exports, webpack_require) {
"use strict";
eval("\n\n//import name from './base';\n//import React from 'react';\n//import ReactDOM from 'react-dom';\n//import ajax from 'ajax';\n//let result = ajax('/ajax');\n\n//ReactDOM.render(<h1 id="result">{result}</h1>, document.getElementById('root'));\n// fetch fetch.js fetch.json fetch文件夹\n//let fetch = require('fetch');\n//console.log(fetch);\n//let get = require('../dist/bundle.js');\n//get.getName();\nconsole.log('hello');\n\nvar name = 'zfpx';\nconsole.log(name);\nif (true) {\n  var s = 'ssssssssssssssssssssssss';\n  console.log(s);\n  console.log(s);\n  console.log(s);\n  console.log(s);\n}\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ })
/******/ });

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

React里的Vuex使用案列

Vue项目分环境打包步奏详解

The above is the detailed content of Detailed explanation of the use of webpack v4. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor