Koa2 webpack all-in-one environment for universal development
koa2、webpack、hmr、isomorphic、server-side-render
Koa-Webpack-Server is all-in-one environment for koa2 and webpack2/3 development.
export
ed from the entry
file in your webpack server side config.This package is usually used to build a universal/isomorphic SPA applications(React、Vue、Angular) using koa and webpack as setback, making universal/isomorphic web-app development super easy.
For complete examples please refer to:
Noted: This package is still on early stage.
yarn add koa-webpack-server --dev
server.js
const Koa = require('koa');
const webpack = require('webpack');
const { webpackServer } = require('koa-webpack-server');
const configs = require('../config/webpack.dev.config');
// 👆 array of webpack configurations(client and server)
const app = new Koa();
const options = {
compilers: webpack(configs),
dev: {
noInfo: false,
quiet: false,
serverSideRender: true,
},
};
// wire webpack-dev-middleware、webpack-hot-middleware to app and start webpack-hot-server
webpackServer(app, options).then(({ middlewares }) => {
// hot-middlewares: you may try making any changes from middlewares,
// it will automatically rebuild and reload,
// so that you don't have to reboot your server to see the changes.
const { logger, render } = middlewares;
app.use(logger);
app.use(render);
app.listen(3000, () => {
console.log('server started at port 3000');
});
}).catch((err) => {
});
middlewares.js
// all middlewares are 'AsyncFunction's
const logger = async (ctx, next) => {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
console.log(`[${ctx.method}][${ms}ms] ${ctx.url}`);
}
export logger;
// you may try making any changes in middlewares, for example,
// change 'Hello World.' to 'Hello World!' and see what's happening.
const render = async (ctx, next) => {
ctx.body = `
<!doctype html>
<html>
<head><title>koa-webpack-server</title></head>
<body><div>Hello World.</div></body>
</html>
`;
await next();
}
export render;
For usage detail please refer to basic examples.
const options = {
compilers: Object, // [Required] webpack compiler
serverName: String, // webpack server config name, default 'server'
dev: Object, // webpack-dev-middleware options
hot: Object, // webpack-hot-middleware options
server: Object, // hot server options
}
webpack-dev-middleware options.
When serverSideRender
is set to true
, webpackStats is accessible from ctx.state.webpackStats
.
app.use(async (ctx, next) => {
const assetsByChunkName = ctx.state.webpackStats.toJson().assetsByChunkName;
// do something with assetsByChunkName
})
For more information please refer to: server-side-rendering.
webpack-hot-middleware options.
const server = {
use: Boolean, // use hot development middleware? default is true
}
MIT