Skip to content

Instantly share code, notes, and snippets.

@fobos
Last active November 10, 2016 17:57
Show Gist options
  • Save fobos/41058aa7c6fbf849908713e82520a7e7 to your computer and use it in GitHub Desktop.
Save fobos/41058aa7c6fbf849908713e82520a7e7 to your computer and use it in GitHub Desktop.
Yet another realization of elm-app start script
const pathExists = require('path-exists');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('../config/webpack.config.dev');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const clearConsole = require('react-dev-utils/clearConsole');
const openBrowser = require('react-dev-utils/openBrowser');
const detect = require('detect-port');
const DEFAULT_PORT = 3000;
process.env.NODE_ENV = 'development';
if (pathExists.sync('elm-package.json') === false) {
console.log('Please, run the build script from project root directory');
process.exit(0);
}
detect(DEFAULT_PORT)
// Configure compiler
.then(function(unoccupiedPort) {
// http://webpack.github.io/docs/node.js-api.html#the-long-way
const compiler = webpack(config);
compiler.plugin('invalid', compilingInProgress);
compiler.plugin('done', function (stats) {
if (stats.hasErrors() || stats.hasWarnings()) {
compilationError(stats);
} else {
compilationDone(unoccupiedPort);
}
});
return {
port: unoccupiedPort,
compiler: compiler
};
})
// Launch WebpackDevServer.
.then(function (config) {
const devServer = new WebpackDevServer(config.compiler, {
hot: true,
inline: true,
publicPath: '/',
quiet: true
});
devServer.listen(config.port, function (err) {
if (err) {
return console.log(err);
}
});
return config.port;
})
.then(function (port) {
openBrowser('http://localhost:' + port + '/');
})
.catch(function (err) {
console.log(err);
});
function compilingInProgress() {
clearConsole();
console.log('Compiling...');
}
function compilationDone(port) {
clearConsole();
console.log(chalk.green('Compiled successfully!'));
if (DEFAULT_PORT !== port) {
console.log(chalk.yellow('Default port ' + DEFAULT_PORT + ' is already busy, we will use ' + unoccupiedPort));
}
console.log('\nThe app is running at:');
console.log('\n ' + chalk.cyan('http://localhost:' + unoccupiedPort + '/'));
console.log('\nTo create production build, run:');
console.log('\n elm-app build');
}
function compilationError(stats) {
clearConsole();
console.log(chalk.red('Compilation failed.\n'));
const json = formatWebpackMessages(stats.toJson({}, true));
json.errors.forEach(function (message) {
console.log(message);
console.log();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment