How to operate dev and prd in webpack
This time I will show you how to operate dev and prd in webpack, and what are the precautions for operating dev and prd in webpack. 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, here you go~
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
This time The mode configuration item is introduced in the new version, and developers can choose between none, development (development) and production (product) modes. This configuration item uses production mode by default.
The development mode gives you the ultimate development experience, including browser debugging related tools, extremely fast incremental compilation, and rich and comprehensive error information...
The production mode includes a lot of release optimization, code compression, smooth runtime optimization, elimination of development-related code, ease of use, etc.
none No Using the default is equivalent to the original state of all self-configurations in the old version.
#eg:
webpack --mode development
Usage
Some Plugin options are now validated
CLI has been move to webpack-cli, you need to install webpack-cli to use the CLI
The ProgressPlugin (--progress) now displays plugin names
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} } ] } ] }
The writing methods of these three 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 for the following configuration
{ test: /\.jpeg$/, use: { loader:'url-loader', options:{ limit:1024, name:[path][name].[ext], outputPath:img/ publicPath:output/' } } }
Develop necessary loader&plugins
css-loader
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 common css code
It will move the *.css referenced in all entry chunks (entry chunks) to independent and separate CSS files. Therefore, your styles will no longer be embedded in the JS bundle, but will be placed in a separate CSS file (i.e. styles.css). If your style files are larger in size, this will make early loading faster because the CSS bundle will be loaded in parallel with the 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>{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中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to operate dev and prd in webpack. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Vivo has not yet publicly announced the name of the X100 successor, but various teasers on its official Weibo profileare already talking about the next generation of flagship cameras, specifically the sensor technology that will replace the Sony IMX9

The snmp protocol is a simple network management protocol. This protocol can support the network management system and is used to monitor whether the devices connected to the network have any situation that causes management concern. However, many users have recently reported that the win10 installation of snmp failed with the error code 0x8024402C. what to do? Users can start Powershell as an administrator to set up. Let this site carefully introduce to users the solution to the error code 0x8024402C when installing snmp in win10. Solution to win10 snmp installation failure error code 0x8024402C 1. Start Powershell as administrator 1. The first step is to run the win10 system

Carla is an open source autonomous driving simulation platform designed for developing and testing autonomous driving algorithms. The following is a detailed tutorial for installing Carla on Ubuntu20.04 system: Install dependencies: Open a terminal window and run the following command to install Carla’s dependencies: sudoaptupdatesudoaptinstall-ybuild-essentialclang-10llvm-10python3-pippython3-devlibpng-devlibjpeg-devlibtiff5-devlibopenexr -devlibhdf5-devlibsquish-de

Vue is an excellent JavaScript framework that can help us quickly build interactive and efficient web applications. Vue3 is the latest version of Vue, which introduces many new features and functionality. Webpack is currently one of the most popular JavaScript module packagers and build tools, which can help us manage various resources in our projects. This article will introduce how to use Webpack to package and build Vue3 applications. 1. Install Webpack

Differences: 1. The startup speed of the webpack server is slower than that of Vite; because Vite does not require packaging when starting, there is no need to analyze module dependencies and compile, so the startup speed is very fast. 2. Vite hot update is faster than webpack; in terms of HRM of Vite, when the content of a certain module changes, just let the browser re-request the module. 3. Vite uses esbuild to pre-build dependencies, while webpack is based on node. 4. The ecology of Vite is not as good as webpack, and the loaders and plug-ins are not rich enough.

With the continuous development of web development technology, front-end and back-end separation and modular development have become a widespread trend. PHP is a commonly used back-end language. When doing modular development, we need to use some tools to manage and package modules. Webpack is a very easy-to-use modular packaging tool. This article will introduce how to use PHP and webpack for modular development. 1. What is modular development? Modular development refers to decomposing a program into different independent modules. Each module has its own function.

Tiny Windows 11 While many people like the look or feel of Windows 11, some just want to cut back on what they consider to be bloat because their hardware may not be powerful enough to run the new operating system smoothly, or just for fun. A popular third-party Windows 11 tweak and customization app called ThisIsWin11 (TIW11) evolved into Debloos or DebloatOS, which, as the name suggests, allows the operating system to debloat. If someone isn't comfortable tweaking things themselves with it, they can also opt for Tiny11, which was released earlier today. This stripped-down Windows11Pro22H2mod requires 8G

Compiling and installing PCL (PointCloudLibrary) is a way to install on Ubuntu with custom options. Here is a basic tutorial: Install dependencies: Before you start compiling PCL, you need to install some necessary dependencies. Open a terminal and run the following command: sudoapt-getupdatesudoapt-getinstallgitbuild-essentiallinux-libc-devcmakecmake-guilibusb-1.0-0-devlibusb-devlibudev-devmpi-default-devopenmpi-bin
