Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Koa 开发服务器和热更实现 #539

Closed
nuintun opened this issue Mar 2, 2021 · 0 comments
Closed

Koa 开发服务器和热更实现 #539

nuintun opened this issue Mar 2, 2021 · 0 comments

Comments

@nuintun
Copy link
Owner

nuintun commented Mar 2, 2021

dev.js

/**
 * @module dev
 * @license MIT
 * @author nuintun
 * @author yiminghe
 * @description Webpack dev middleware for koa2
 * @see https://github.com/yiminghe/koa-webpack-dev-middleware/blob/2.x/src/index.js
 */

'use strict';

const expressMiddleware = require('webpack-dev-middleware');

module.exports = (compiler, options) => {
  const middleware = expressMiddleware(compiler, options);

  const devMiddleware = async (ctx, next) => {
    ctx.remove('Content-Type');

    await middleware(
      ctx.request,
      {
        locals: ctx.state,
        status(statusCode) {
          ctx.status = statusCode;
        },
        set(field, value) {
          ctx.response.set(field, value);
        },
        get(field) {
          return ctx.response.get(field);
        },
        send(content) {
          ctx.body = content;
        }
      },
      next
    );
  };

  Object.keys(middleware).forEach(key => (devMiddleware[key] = middleware[key]));

  return devMiddleware;
};

hot.js

/**
 * @module hot
 * @license MIT
 * @author nuintun
 * @author kimjuny
 * @description Webpack hot middleware for koa2
 * @see https://github.com/kimjuny/koa-webpack-server/blob/master/src/hot.js
 */

'use strict';

const { PassThrough } = require('stream');
const expressMiddleware = require('webpack-hot-middleware');

module.exports = (compiler, options) => {
  const middleware = expressMiddleware(compiler, options);

  const hotMiddleware = async (ctx, next) => {
    const stream = new PassThrough();

    ctx.body = stream;

    const locals = ctx.state;
    const end = stream.end.bind(stream);
    const write = stream.write.bind(stream);
    const writeHead = (status, headers) => {
      ctx.status = status;

      ctx.set(headers);
    };

    await middleware(ctx.req, { locals, writeHead, write, end }, next);
  };

  Object.keys(middleware).forEach(key => (hotMiddleware[key] = middleware[key]));

  return hotMiddleware;
};
Repository owner locked and limited conversation to collaborators Mar 2, 2021
@nuintun nuintun closed this as completed Mar 2, 2021
@nuintun nuintun pinned this issue Mar 2, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant