Skip to content

Instantly share code, notes, and snippets.

@troutowicz
Last active August 29, 2015 14:15
Show Gist options
  • Save troutowicz/bfd0e4eb0633ed77834e to your computer and use it in GitHub Desktop.
Save troutowicz/bfd0e4eb0633ed77834e to your computer and use it in GitHub Desktop.
Launch wepack-dev-server without CLI. Provides ability to dynamically set server IP and port
'use strict';
/*
* Equivalent of:
*
* webpack-dev-server
* --config config/webpack/dev-server.config.js
* --progress
* --colors
* --host [IP]
* --port [PORT]
* --hot
* --inline
*/
var WebpackDevServer = require('webpack-dev-server');
var Webpack = require('webpack');
var HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
// grab IP and port from project conf
var Conf = require('../../lib/conf');
// grab webpack options
var wpOpt = require('./dev-server.config.js');
var options = wpOpt.devServer;
var protocol = 'http';
var port = Conf.get('webpack_port');
var host = Conf.get('domain');
var devClient = [
require.resolve('webpack-dev-server/client/') + '?' + protocol + '://' + host + ':' + port,
'webpack/hot/dev-server'
];
var chars = 0;
function goToLineStart(nextMessage) {
var str = '';
for (; chars > nextMessage.length; chars--) {
str += '\b \b';
}
chars = nextMessage.length;
for (var i = 0; i < chars; i++) {
str += '\b';
}
if (str) {
process.stderr.write(str);
}
}
wpOpt.entry = devClient.concat(wpOpt.entry);
wpOpt.output.path = '/';
wpOpt.context = process.cwd();
wpOpt.plugins.push(new HotModuleReplacementPlugin());
wpOpt.plugins.push(new ProgressPlugin(function(percentage, msg) {
if (percentage < 1) {
percentage = Math.floor(percentage * 100);
msg = percentage + '% ' + msg;
if (percentage < 100) {
msg = ' ' + msg;
}
if (percentage < 10) {
msg = ' ' + msg;
}
}
goToLineStart(msg);
process.stderr.write(msg);
}));
options.stats.colors = true;
options.publicPath = wpOpt.output.publicPath;
options.outputPath = '/';
options.filename = wpOpt.output.filename;
options.hot = true;
options.contentBase = process.cwd();
new WebpackDevServer(new Webpack(wpOpt), options).listen(port, host, function(err) {
if (err) {
throw err;
}
console.log(protocol + '://' + host + ':' + port + '/');
console.log('webpack result is served from ' + options.publicPath);
console.log('content is served from ' + options.contentBase);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment