webpack
提供了webpack-dev-server
模塊來啓動一個簡單的web服務器,爲了更大的自由度咱們能夠本身配置一個服務器,下面介紹如何用koa2
來實現。javascript
wepack-dev-middleware
把webpack處理後的配置文件傳遞給服務器,不過咱們在使用它以前,須要把它改形成koa中間件。java
安裝wepack-dev-middleware
:node
npm install wepack-dev-middleware -D
封裝成koa中間件。devMiddleware.js
:webpack
// 改形成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
生成的模塊是寫入到內存中的,因此咱們須要修改開發環境中的output
配置項:web
// webpack.dev.conf.js output: { filename: '[name].[hash].js', path: '/' // 修改此配置項 }
安裝webpack-hot-middleware
:npm
npm install webpack-hot-middleware -D
封裝成koa中間件。hotMiddleware.js
:json
// 改形成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;
安裝koa:bash
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:app
"scripts": { "server": "node server.js --mode development" }
啓動服務器:
npm run server
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", }