媒介
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",
}