上一节,学习到经过webpack-dev-server
搭配HotModuleReplacementPlugin
插件能够实现不刷新页面的模块热更新。html
最后讲解原理的时候,咱们知道webpack-dev-server
在内部使用Express
搭建搭建了一个小型Node
服务来接收处理后的文件,那是什么程序传递文件的呢?node
就是webpack-dev-middleware
。webpack
定义:web
webpack-dev-middleware
是一个容器(wrapper
),它能够把webpack
处理后的文件传递给一个服务器(server
)。
webpack-dev-server
在内部使用了它,同时,它也能够做为一个单独的包来使用,以便进行更多自定义设置来实现更多的需求。express
咱们也使用Express,搭配webpack-dev-middleware
来实现文件更新功能npm
咱们先搭建一个基础项目骨架json
├── dist
│ └── index.html
├── package.json
├── src
│ ├── block.js
│ └── index.js
└── webpack.dev.config.js
复制代码
由于是在开发环境须要热更新,因此依然是webpack.dev.config.js
bash
咱们来简单配置一下:服务器
npm i webpack webpack-cli webpack-dev-middleware express --save-dev
复制代码
webpack.dev.config.jsapp
const path = require('path');
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
}
};
复制代码
server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const path = require('path');
const app = express();
const config = require('./webpack.dev.config.js');
const compiler = webpack(config);
// const DIST_DIR = path.join(__dirname, "dist")
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
// 使用静态资源目录,才能访问到/dist/idndex.html
app.use(express.static(config.output.path))
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
复制代码
/src/index.js
'use strict'
import { test } from './block.js'
document.write('hello world~')
test()
复制代码
/src/block.js
'use strict'
module.exports = {
test: function () {
console.log(12345)
}
}
复制代码
/dist/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack-dev-middleware</title>
<script src="./index.js"></script>
</head>
<body>
</body>
</html>
复制代码
package.json 增长一个命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "server": "node server.js"
},
复制代码
npm run server
复制代码
咱们能够看到已经编译成功,直接访问http://localhost:3000/
而后咱们修改一下block.js
'use strict'
module.exports = {
test: function () {
console.log(123456)
}
}
复制代码
能够看到从新编译了,这时候咱们手动刷新下页面,便可看到修改。
以上就是webpack-dev-middleware
的简要学习,咱们发现这个中间件也仅仅只是完成了打包文件向服务器的传输,没有实现热加载也没有实现热更新。
这是不能知足开发需求的,因此接下来我要学习一下webpack-hot-middleware
了。
webpack学习之路(五)loader初识及经常使用loader介绍
webpack学习之路(四)webpack-hot-middleware实现热更新
webpack学习之路(二)webpack-dev-server实现热更新
webpack学习之路(一)基础配置 I am moving forward.