webpack工程化10(使用middleware搭建开发环境
2018-12-31 本文已影响18人
Mr绍君
之前我们说过webpack搭建服务有三种方式,除了devServer还有一种更加自由的方式,就是express + webpack-dev-middleware,我们今天来说说这种搭建服务的方法。
我们直接来看demo(demo在wepack工程化09(webpack搭建开发环境和生产环境)这篇文章的基础上进行配置)
npm install express opn webpack-dev-middleware webpack-hot-middleware http-proxy-middleware connect-history-api-fallback -D
我们先把项目中需要用的包先进行一下安装。
const express = require('express')
const opn = require('opn')
const app = express()
const port = 3000
app.listen(port, function() {
console.log('success')
opn('http://localhost:'+ port)
})
我们先配置express,这段配置的意思就是启动一个服务,并监听3000端口,同时打开浏览器。(此时的服务并没有跟我们的配置挂钩,而我们安装的middleware就是把配置文件跟express挂钩的)
const express = require('express')
const webpack = require('webpack')
const opn = require('opn')
const app = express()
const port = 3000
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const proxyMiddleware = require('http-proxy-middleware')
const historyApiFallback = require('connect-history-api-fallback')
const proxyTable = require('./proxy')
for(let context in proxyTable) {
app.use(proxyMiddleware(context, proxyTable[contenxt]))
}
const config = require('./webpack.dev.conf')
const compiler = webpack(config)
app.use(historyApiFallback(require('./historyfallback')))
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))
app.use(webpackHotMiddleware(compiler))
app.listen(port, function() {
console.log('success')
opn('http://localhost:'+ port)
})
我们先把配置文件导入,然后通过webpack方式对配置文件进行处理。
const config = require('./webpack.dev.conf')
const compiler = webpack(config)
然后再通过app.use中间件来处理。
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))