Skip to content

Instantly share code, notes, and snippets.

@chrismatix
Last active September 13, 2017 18:02
Show Gist options
  • Save chrismatix/e0861a950789dff52467365d92ebafc1 to your computer and use it in GitHub Desktop.
Save chrismatix/e0861a950789dff52467365d92ebafc1 to your computer and use it in GitHub Desktop.
webpack dev middleware with multiple webroots
const express = require('express');
const webpack = require('webpack');
const DashboardPlugin = require('webpack-dashboard/plugin');
const chalk = require('chalk');
const path = require('path');
const config = {
dev: {
host: 'localhost',
port: 3000
}
};
const root = path.resolve(__dirname, './build');
// default port where dev server listens for incoming traffic
const port = process.env.PORT || config.dev.port;
process.env.CONFIG = process.env.CONFIG || 'development';
const app = express();
let configsToRun = [require('config1.babel'), require('config2.babel')];
const [command, start, ...args] = process.argv;
if (args.length === 1) {
configsToRun = configsToRun.filter((config) => config.name === args[0]);
if (configsToRun.length === 0) {
throw new Error('config with name ' + args[0] + ' not found');
} else {
console.log(chalk.green(`running only ${args[0]} bundle`));
}
} else {
console.log(chalk.green('running all packages'));
}
app.use(require('connect-history-api-fallback')({
rewrites: configsToRun.reverse().map((config) => {
const publicPath = config.output.publicPath;
console.info('fallback for ', publicPath);
// match the config's public path, but do not match for dots as they are file requests
return {
from: new RegExp(publicPath + '[^.]*$'),
to: `${publicPath}/index.html`
}
}), verbose: true
}));
// Dev Server
configsToRun.forEach((config) => {
const compiler = webpack(config);
compiler.apply(new DashboardPlugin({ port: 3000 }));
const middleware = require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
noInfo: true,
stats: { colors: true }
});
app.use(middleware);
// Enables HMR
app.use(require('webpack-hot-middleware')(compiler, {
log: () => {
}
}));
middleware.waitUntilValid(() => {
console.log(chalk.white(`> ${config.name} listening at ${uri}${config.output.publicPath}`));
});
});
const uri = `http://${config.dev.host}:${port}`;
app.listen(port, (err) => {
if (err) {
console.log(err)
}
});
@chrismatix
Copy link
Author

This allows you to run multiple webpack configs in parallel and with separate webroots. Say you have a react app, but want to use the same setup to create and test an embedded version you would just create a separate webpack config.

This one even takes cmd line arguments so that you can only run bundles that you are interested in like so node dev-server.js embed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment