前言
webpack
提供了webpack-dev-server
模块来启动一个简单的web服务器,为了更大的自由度我们可以自己配置一个服务器,下面介绍如何用koa2
来实现。
wepack-dev-middleware
wepack-dev-middleware
把webpack处理后的配置文件传递给服务器,不过我们在使用它之前,需要把它改造成koa中间件。
安装wepack-dev-middleware
:
npm install wepack-dev-middleware -D
封装成koa中间件。devMiddleware.js
:
// 改造成koa中间件
const webpackDev = require('webpack-dev-middleware');
const devMiddleware = (compiler, opts) => {
const middleware = webpackDev(compiler, opts);
return async (ctx, next) => {
await middleware(ctx.req, {
end: (content) => {
ctx.body = content;
},
setHeader: (name, value) => {
ctx.set(name, value);
}
}, next);
};
};
module.exports=devMiddleware;
webpack-hot-middleware
webpack-hot-middleware
模块主要用来实现热替换,也就是说我们在修改文件后只需刷客户端页面就能看到效果了。因为通过webpack-hot-middleware
生成的模块是写入到内存中的,所以我们需要修改开发环境中的output
配置项:
// webpack.dev.conf.js
output: {
filename: '[name].[hash].js',
path: '/' // 修改此配置项
}
安装webpack-hot-middleware
:
npm install webpack-hot-middleware -D
封装成koa中间件。hotMiddleware.js
:
// 改造成koa中间件
const webpackHot = require('webpack-hot-middleware')
const PassThrough = require('stream').PassThrough;
const hotMiddleware = (compiler, opts) => {
const middleware = webpackHot(compiler, opts);
return async (ctx, next) => {
let stream = new PassThrough();
ctx.body = stream;
await middleware(ctx.req, {
write: stream.write.bind(stream),
writeHead: (status, headers) => {
ctx.status = status;
ctx.set(headers);
}
}, next);
};
};
module.exports = hotMiddleware;
koa2实现服务器
安装koa:
npm install koa -D
server.js
:
const Koa = require('koa');
const webpack = require('webpack'); // webpack模块
const config = require('./webpack.dev.conf'); // 开发环境模块
// 中间件容器,把webpack处理后的文件传递给一个服务器
const devMiddleware = require('./devMiddleware');
// 在内存中编译的插件,不写入磁盘来提高性能
const hotMiddleware = require('./hotMiddleware');
const compiler = webpack(config);
const app = new Koa();
app.use(devMiddleware(compiler, {
publicPath: config.output.publicPath // '/'
}));
app.use(hotMiddleware(compiler));
app.listen(3000);
console.log('lostening on port 3000');
配置package.json:
"scripts": {
"server": "node server.js --mode development"
}
启动服务器:
npm run server
通过koa2中间件配置
koa2社区也提供了封装好的中间件,例如koa-webpack
和koa-webpack-middleware
,不过后者已经好久没有维护了,下面我们用koa-webpack
来简化配置。
安装依赖:
npm install koa-webpack -D
修改server.js
:
const Koa = require('koa');
const middleware = require('koa-webpack');
const webpack = require('webpack');
const config = require ('./webpack.dev.conf.js');
const compiler = webpack(config);
const app = new Koa();
app.use(middleware({
compiler: compiler
}));
app.listen(3000);
console.log('lostening on port 3000');
模块版本:
"devDependencies": {
"koa": "^2.5.0",
"koa-webpack": "^3.0.0",
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"webpack-dev-middleware": "^3.0.0",
"webpack-hot-middleware": "^2.21.1",
}