koa2 webpack-dev-middleware如何访问编译在内存中的静态资源文件

var config = require('./config')
var path = require('path')
var webpack = require('webpack')

var webpackConfig = require('./webpack.dev.conf')

var compiler = webpack(webpackConfig)


//koa2
const Koa = require("koa")
const koaStatic = require("koa-static")
const koaWebpackMiddleware = require("koa-webpack")

const app = new Koa();

app.use(koaStatic(webpackConfig.output.publicPath));
app.use(koaStatic(webpackConfig.output.publicPath));


app.use(koaWebpackMiddleware({
  compiler: compiler,
  dev: {
    publicPath: webpackConfig.output.publicPath,
    headers: { 'Content-Type': 'text/html; charset=utf-8' },
    stats: {
      colors: true
    },
    serverSideRender: false
  },
  hot: {
    log: console.log,
    path: '/__webpack_hmr',
    heartbeat: 10 * 1000
  }
}))
// app.use(async (ctx, next) => {
//   await next();
//   console.log(ctx)
//   if (!ctx.body && ctx.status == 404) {
//     ctx.body = ctx.status;

//     ctx.status = 404;
//   }
// });
app.listen(8080, () => {});

在以上webpack中在/dist文件夹中编译出了一个文件 /dist/index.html
但是在访问 localhost:8080/dist/index.html的时候却返回not found,不知道我到底是少哪一步呢

阅读 5.9k
3 个回答

最好贴一下webpack.dev.conf的配置文件,一般访问的时候不需要加/dist,具体可以参考一下我这里的配置:webpack.config.js

新手上路,请多包涵

请问楼主解决这个问题了么?我启动了 hmr, 但是似乎服务端没有生成 html 文件...

你可以加一个中间件, 当时开发环境时, 根据请求路径, 在内存中查找对应的文件返回, 没有就next(),贴一下代码:

app.use(async (ctx, next) => {
    if (isProd) return await next()
    let p = path.resolve(__dirname, 'dist' + ctx.req.url)
    try {
        
        let file = devMiddleware.fileSystem.readFileSync(p, 'utf-8')
        if (file) {
            return (ctx.body = file)
        } else {
            await next()
        }
    } catch (e) {
        await next()
    }
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题