Created
July 9, 2017 22:43
-
-
Save kohlmannj/2277cad5602c802480c46710ede77aa8 to your computer and use it in GitHub Desktop.
An example of using BrowserSync, webpack-dev-middleware, and webpack-hot-middleware together in a script that boots up a custom dev server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env node | |
/* eslint-env node */ | |
// Boot it up with: | |
// $ node customDevServer.js | |
// ...or: | |
// $ chmod +X customDevServer.js | |
// $ ./customDevServer.js | |
const webpack = require('webpack'); | |
const webpackDevMiddleware = require('webpack-dev-middleware'); | |
const webpackHotMiddleware = require('webpack-hot-middleware'); | |
const browserSync = require('browser-sync'); | |
// Set `process.env.NODE_ENV` BEFORE calling the Webpack CLI | |
process.env.NODE_ENV = 'development'; | |
// Some options I'm using in my Webpack config function | |
const options = { | |
hot: true, // should always be true --- BrowserSync without HMR is pretty pointless | |
devServer: true, | |
browserSync: true | |
}; | |
// Get the Webpack config (with options) | |
const config = require('../webpack.config.js')(options); | |
const bundler = webpack(config); | |
// Run Browsersync and use middleware for Hot Module Replacement | |
const middleware = [ | |
webpackDevMiddleware(bundler, { | |
// IMPORTANT: dev middleware can't access config, so we should | |
// provide publicPath by ourselves | |
publicPath: config.output.publicPath, | |
index: 'index.html', | |
// pretty colored output | |
stats: { colors: true } | |
// for other settings: | |
// @see https://webpack.js.org/guides/development/#webpack-dev-middleware | |
}) | |
]; | |
if (options.hot === true) { | |
// bundler should be the same as above | |
middleware.push(webpackHotMiddleware(bundler)); | |
} | |
browserSync({ | |
port: 3002, | |
notify: false, | |
server: { | |
baseDir: config.output.path, | |
middleware | |
}, | |
// No need to watch '*.js' here, webpack will take care of it | |
// for us, including full page reloads if HMR won't work. | |
// (Not convinced we _really_ need BrowserSync to watch things, but anyway... | |
files: [ | |
'css/*.css', | |
'*.html' | |
] | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment