Skip to content

Instantly share code, notes, and snippets.

@pts-moog16
Last active May 6, 2021 20:48
Show Gist options
  • Save pts-moog16/be60adf03a8185176a25b3153e4aa129 to your computer and use it in GitHub Desktop.
Save pts-moog16/be60adf03a8185176a25b3153e4aa129 to your computer and use it in GitHub Desktop.
Gulp task for starting webpack-dev-server
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config.js');
const browserSync = require('browser-sync');
// a nice npm module written to have BrowserSync work with Webpack
// and webpack-dev-server
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const renderTemplate = require('./build/gulp/template');
const clients = require('./build/gulp/clients')();
let browserSyncInstance;
gulp.task("webpack-dev-server", ['watch', 'renderDevTemplate', 'buildStyles'], () => {
const servername = 'bsserver'; // this name can be anything
const bsConfig = {
host: 'localhost',
port: 4000 // 4000 (my API server was on 3001, so anything different)
};
const bspluginConfig = {
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false,
// this name can be anything, it is just needed for the callback seen below
name: servername,
// This gets the BrowserSync Instance
callback: () => { browserSyncInstance = browserSync.get(servername) }
};
const _config = Object.assign(webpackConfig(), {
plugins: [
new BrowserSyncPlugin(bsConfig, bspluginConfig), // hook up BrowserSync for css updating
new webpack.HotModuleReplacementPlugin(), // to enable HMR for webpack-dev-server
new webpack.NamedModulesPlugin() // needed for HMR error handling
]
});
const config = webpack(_config);
// start off webpack dev server just like in the docs and examples
// useful links:
// https://webpack.github.io/docs/usage-with-gulp.html
// https://github.com/webpack/webpack-with-common-libs/blob/master/gulpfile.js
new WebpackDevServer(config, _config.devServer).listen(8080, 'localhost', (err) => {
if(err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment