在咱們開發的過程當中,咱們會使用webpack-dev-server
實現自動刷新,webpack-dev-server
會把編譯後的文件所有保存在內存裏,而不會寫入到文件目錄內。但當咱們的開發是前端和後端在一個項目裏的時候就不行了。咱們能夠除了可使用webpack結合express實現自動編譯刷新,還可使用webpack結合koa實現自動編譯刷新前端
首先就是配置webpack的配置。新建一個webpack.config.js
文件webpack
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: {
main: ['./src/main.js']
},
mode: 'development',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'js/[name].js',
publicPath: '/'
},
resolve: {
extensions: ['.js']
}
}
複製代碼
這裏和咱們日常使用webpack的配置同樣web
koa-webpack
這個模塊,咱們無需再設置koa-webpack-middleware
,使用起來很是簡單const Koa = require('koa')
const serve = require('koa-static')
const webpack = require('webpack')
const config = require('./webpack.config.js')
const koaWebpack = require('koa-webpack')
const {
resolve
} = require('path')
const app = new Koa()
const port = process.env.PORT || 3000
async function start() {
const compiler = webpack(config)
try {
const middleware = await koaWebpack({
compiler
})
app.use(middleware)
app.use(serve(resolve(__dirname, './public')))
app.listen(3000)
} catch (e) {
console.log(e)
}
}
start()
複製代碼
這樣,咱們在開發的時候,前端和後端都在同一個服務裏運行了express