当前位置:网站首页>WDS must know and know
WDS must know and know
2022-06-21 15:55:00 【maic】
stay webpack Build local services in , The most important plug-in webpack-dev-server, We call it WDS, It takes on the role of Module thermal loading 、 The local service 、 The interface agent And other very important functions .
This paper is the author's research on wds Some understanding and understanding of , Hope to help in the project .
Text begins ...
Before reading this article , This article will roughly understand from the following aspects wds
1、 understand wds What is it?
2、wds stay webpack How to use
3、 Project use wds What is it like
4、 About configuration devServer Some common configurations of , Agent etc.
5、wds How to realize the module hot loading principle
understand webpack-dev-server
seeing the name of a thing one thinks of its function , This is a development environment Used under The local service , It assumes the role of providing front-end static services
First, we quickly set up a project , Create a project webpack-07-wds perform npm init -y, Then install the basic supported plug-ins
npm i webpack webpack-cli html-webpack-plugin webpack-dev-server -D
Create a webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
},
plugins: [new htmlWebpackPlugin({
template: './public/index.html'
})]
}
Create in the root directory public, newly build html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>webpack-for-dev-server</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
We write a simple code in the entry file
// index
(() => {
const appDom = document.getElementById('app');
appDom.innerHTML = 'hello webpack for wds'
})()
We have prepared the content , Now we need to start wds, So we need to be in package.json Start service
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack server"
},
perform npm run start

Everything will be fine , It turns out that one line of command is enough
But behind this line of command is actually webpack-cli Helped us do something , In fact, .bin Under the table of contents , When you execute the command ,webpack Will enable notification webpack-dev-server Opening service , adopt webpack according to webpack.config.js The configuration information of compiler, And then give it to webpack-dev-server Handle
Refer to official documentation webpack-dev-server[1]
New root server.js
// server.js
const webpack = require('webpack');
const webpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config.js');
// webpack Handle portal configuration related files
const compiler = webpack(webpackConfig);
// devServer Related configuration of
const devServerOption = {
port: 8081,
static: {
directory: path.join(__dirname, 'public')
},
compress: true // Turn on gizps Compress public Medium html
};
const server = new webpackDevServer(devServerOption, compiler);
const startServer = async () => {
console.log('server is start');
await server.start();
}
startServer();
Terminal execution node server.js Or in package.json Middle configuration , perform npm run server
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack server",
"server": "node ./server.js"
}
Open the page http://localhost:8081 Address , Found to be ok Of
We note that you can use webpack server Start the service , This is mainly webpack-cli The order of server[2]
About setting the corresponding environment in the command line , You may see in previous projects ,process.env.NODE_ENV This setup
You can cli Configure in the command , Note that it can only be set at the front , Cannot be set in the following way webpack server NODE_ENV=test NODE_API=api, Otherwise it will be invalid
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "NODE_ENV=test NODE_API=api webpack server",
"server": "node ./server.js"
},
stay webpack.config.js You can see the set parameters in
// webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin')
console.log(process.env.NODE_ENV, process.env.NODE_API) // test api
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js'
},
plugins: [new htmlWebpackPlugin({
template: './public/index.html'
})]
}
You can set --node-env xxx Environment parameters to specify environment variables
"start:test": "webpack server --node-env test",
For more parameter settings, please refer to the official cli[3]
wds stay webpack The use of
We use a server.js, Through command line mode , call webpack-dev-serverAPI To start a local static service , But actually , stay webpack Directly in the configuration devServer[4] Just configure it in the interface .
Learn about several common configurations
portSpecify the port to open the pageclientoverlay When the program is wrong , Browser page full screen warning webSocketURL Allow the designation of websocket The server
progressLaunch the development environment gizp Compress static htmlhistoryApiFallbackWhen the routing mode is history when , You have to set this , Otherwise, the front-end refreshes directly 404 pagehotModule thermal loading , Need to combinemodule.hot.accept('xxx/xxx')Specify a module hot load module.hot.acceptopen When we start the local service , Automatically open the browser for the specified configuration port
module.exports = {
...
devServer: {
port: '9000',
client: {
progress: true, // Enable gizp
overlay: {
errors: true, // If there is an error, there will be a mask
warnings: false,
},
webSocketURL: {
hostname: '0.0.0.0',
pathname: '/ws',
port: 8080,
protocol: 'ws',
}
},
historyApiFallback: true, // The routing mode used is history when , You have to set this , Otherwise, the front-end refresh will directly 404 page
hot: true, // Module thermal loading , Corresponding modules must cooperate with module.hot.accept('xxx/xxx.js') Specify module hot load
open: true, // When the service is started, the browser is automatically opened by default , You can specify which page to open
}
}
proxy
proxy This is the most contact point in the project , It is also the most troublesome thing for beginners to configure agents , actually proxy The essence is to put the local Interface routing prefix Proxy to the target server environment , You can proxy multiple different environments at the same time , Refer to the following for details
...
module.exports = {
...
devServer: {
...
proxy: {
'/j': {
target: 'https://movie.douban.com', // Acting Douban
changeOrigin: true
},
'/cmc': {
target: 'https://apps.game.qq.com', // Acting King glory official website
changeOrigin: true, // Must add , Otherwise, the proxy interface directly returns html
pathRewrite: { '^/cmc': '/cmc' },
}
}
}
}
We modify index.js
(() => {
const $ = id => document.getElementById(id);
const appDomMovie = $('movie');
const gameDom = $('wang');
// appDom.innerHTML = 'hello webpack for wds,';
// https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=%E7%94%B5%E5%BD%B1&start=0
// Watercress movie
const featchMovie = async () => {
const { data = [] } = await (await fetch('/j/new_search_subjects?sort=U&range=0,10&tags=%E7%94%B5%E5%BD%B1&start=0')).json()
// console.log(data)
const divDom = document.createElement('div');
let str = '';
data.forEach(item => {
const { title, rate } = item;
str += ` <span>${title},${rate}</span>`
})
divDom.innerHTML = str;
appDomMovie.appendChild(divDom);
}
featchMovie();
const wangzherongyao = async () => {
const divDom = document.createElement('div');
// https://apps.game.qq.com/cmc/cross?serviceId=18&filter=tag&sortby=sIdxTime&source=web_pc&limit=20&logic=or&typeids=1%2C2&exclusiveChannel=4&exclusiveChannelSign=8a28b7e82d30142c1a986bb7acdcc068&time=1655732988&tagids=931
// King glory official website
const { data: { items = [] } } = await (await fetch('/cmc/cross?serviceId=18&filter=tag&sortby=sIdxTime&source=web_pc&limit=20&logic=or&typeids=1%2C2&exclusiveChannel=4&exclusiveChannelSign=8a28b7e82d30142c1a986bb7acdcc068&time=1655732988&tagids=931')).json()
let str = '';
console.log(items)
items.forEach(item => {
const { sTitle, sIMG } = item;
str += `<div>
<img src=${sIMG} />
<div>${sTitle}</div>
</div>`
});
divDom.innerHTML = str;
gameDom.appendChild(divDom);
}
wangzherongyao()
})()
The corresponding two interface data have been rendered on the page
For agency, we will often make the following mistakes A few mistakes
The first one is , Multiple interface agents , The first one is directly /agent , This will invalidate the second proxy , Direct interface 404, The priority will match the first one first
{
devServer: {
proxy: {
'/': {
target: 'https://movie.douban.com', // Acting Douban
changeOrigin: true,
},
'/cmc': {
target: 'https://apps.game.qq.com', // Acting King glory official website
changeOrigin: true, // Must add , Otherwise, the proxy interface directly returns html
pathRewrite: { '^/cmc': '/cmc' },
}
}
}
}
The second kind , pathRewriteDo you want to add? , When should I add , I don't know if you found that my first interface interception didn't addpathRewrite, But the effect is the same as the second one .
Now there's a scene , There is a difference between your local test service interface and your online interface , Generally, you develop the joint debugging environment locally , The back-end interface does not follow the common sense , Suppose that the back end of the joint debugging environment is dead and alive and does not agree with the unified interface path ?
Now suppose the back-end interface
Joint commissioning environment :/dev/api/cmc/cross
The online environment is /api/cmc/cross
So you think of the following two options :
1、 stay axios Request interception according to environment variable Add the prefix manually , But this is not a good solution , It is equivalent to packaging the uncertain logic code onto the line , There is a certain risk
2、 Both the development environment and the local joint debugging environment are unified paths , Just in proxy Of pathRewrite Do the processing , The risk is small , It is not easy to cause online interface 404 risk
So this time pathRewrite And that's what happened , Rewrite path , Note that pathRewrite: { '^/cmc': '/dev/cmc' }
We just re - started in the development environment /cmc Interface path , In fact, the code of the code environment is not packaged online
{
devServer: {
proxy: {
'/j': {
target: 'https://movie.douban.com', // Acting Douban
changeOrigin: true,
},
'/cmc': {
target: 'https://apps.game.qq.com', // Acting King glory official website
changeOrigin: true, // Must add , Otherwise, the proxy interface directly returns html
pathRewrite: { '^/cmc': '/dev/cmc' },
}
}
}
}
The third kind of , The lack of changeOrigin:true, Something like this is missingchangeOriginYou can't
devServer: {
proxy: {
'/j': {
target: 'https://movie.douban.com', // Acting Douban
// changeOrigin: true,
pathRewrite: { '^/j': '/j' },
},
'/cmc': {
target: 'https://apps.game.qq.com', // Acting King glory official website
//changeOrigin: true,
pathRewrite: { '^/cmc': '/dev/cmc' },
}
}
}
}
What if multiple routes point to the same server , Don't worry. , There are plans on the official website , You can do this
{
devServer: {
proxy: [
{
context: ['/j', '/cmc'],
target: 'https://movie.douban.com'
}
]
}
}
These are the most commonly used items , In addition, the expanded , For example, it can support local https, Because the default local is http, There is also support for opening a websocket service , Please refer to the official website for more configuration , Or have more special needs , Read in time Official website [5]
WDS Module thermal loading principle (HMR)
Update only the changed contents of the page module , No need to refresh the whole site
It's essentially webpack-dev-server Two services in , One express Static services provided , adopt webpack Go to compiler The dependent file of the entry , Load... In packed memory bundle.js
The second module hot load is a websocket service , adopt socketio, When the source static file changes , A manifest file , This file will record a hash And the corresponding document modification chunk.js, When the file is modified websocket Will send a separate... To the browser ws service , So as to update some modules of the page , For more information, please refer to the official website hot-module-replacement[6]
summary
understand
webpack-dev-serverWhat is it? , It is a static service of a development environmentwebpack-dev-serverstay webpack The use ofAbout
WDSSome common configurations , For example, how to configure interface proxySimple understanding
HMRModule thermal loading , NativewebpackAlthough module hot loading is also provided , howeverwebpack-dev-serverModule hot loading can be realized , Common framework , such asvue, The internal thermal loading is performed byvue-loaderRealized , In the use ofWDSwhen , By default, hot loading is enabled .
Reference material
webpack-dev-server: https://webpack.docschina.org/api/webpack-dev-server/
[2]server: https://github.com/webpack/webpack-cli/blob/master/SERVE-OPTIONS-v4.md
[3]cli: https://webpack.docschina.org/api/cli/
[4]devServer: https://webpack.docschina.org/configuration/dev-server/
[5]Official website : https://webpack.docschina.org/configuration/dev-server/
[6]hot-module-replacement: https://webpack.docschina.org/concepts/hot-module-replacement/
边栏推荐
- 使用APICloud实现文档下载和预览功能
- 高级性能测试系列《3.性能指标、可靠性测试、容量测试、性能测试》
- Select article (039) - when the button is clicked, event What is target?
- Dstream and its basic operating principle
- [pytorch basic tutorial 29] DIN model
- 加密市场「大逃杀」:清算、抛售、挤兑
- What is the confirmation date for the scheduled redemption of financial products?
- Score-Based Generative Modeling through Stochastic Differential Equations
- Write commodity table with JSP
- [number theory] leetcode1006 Clumsy Factorial
猜你喜欢

Baota, a well-known server operation and maintenance software manufacturer, joined dragon lizard community and completed compatibility and adaptation with Anolis OS

Basic concepts of database

真香!十五分钟搞定智能标注、模型训练、服务部署……

【PyTorch基础教程29】DIN模型

建立自己的网站(4)

WEB3 安全系列 || 攻击类型和经验教训

What has paileyun done to embrace localization and promote industrial Internet?

Distributed monomer brought by microservice architecture

Blazor overview and routing

Comprehensive learning notes for intermediate network engineer in soft test (nearly 40000 words)
随机推荐
Graph calculation on nlive:nepal's graph calculation practice
TypeScript(6)函数
Go language - Method
Baota, a well-known server operation and maintenance software manufacturer, joined dragon lizard community and completed compatibility and adaptation with Anolis OS
ABP Framework 5.3.0 版本新增功能和变更说明
Typescript (6) function
C multithreading
Goose factory, everything about ThreadLocal
Tomb. Weekly update of Finance (February 14-20)
The out of the box caching function of angular server-side rendering applications
How can decentralized games attract traditional players?
2 万字 + 30 张图 | 细聊 MySQL undo log、redo log、binlog 有什么用?
目前哪个期货公司开户比较好?请问手续费低、交易又安全?
Soul app focuses on the social needs of generation Z and has won many awards for its outstanding performance in 2021
WDS必知必会
GO语言-type关键字
高级性能测试系列《6.问题解答、应用的发展》
Blazor overview and routing
Blazor概述和路由
Based on Transformer's artificial neural network, the image of organic structure is transformed into molecular structure