Skip to content

Instantly share code, notes, and snippets.

@maheshsenni
Last active May 9, 2016 00:18
Show Gist options
  • Save maheshsenni/a6ab9724a30a9c9ec809ddf12f0d72e3 to your computer and use it in GitHub Desktop.
Save maheshsenni/a6ab9724a30a9c9ec809ddf12f0d72e3 to your computer and use it in GitHub Desktop.
Step 1 - Creating a module bundler with Hot Module Replacement
var mdeps = require('module-deps');
var browserPack = require('browser-pack');
var JSONStream = require('JSONStream');
var fs = require('fs');
var path = require('path');
// express - for serving our app
var express = require('express');
var app = express();
var http = require('http').Server(app);
// parse arugments to get entry point file name and path
var args = process.argv.slice(2);
var entryPointFile;
if (args.length <= 0) {
// check if entry point file is specified when running the command
console.log('Specify an entry point file');
process.exit(1);
} else {
// store the entry point file
entryPointFile = args[0];
}
var moduleDepsJSONStr;
var moduleDepsJSON;
var bundleStr;
var processModuleDepsStr = function(str) {
// since JSON is from stream, we need to store
// it in a variable until the end of the stream is reached
moduleDepsJSONStr += str;
};
var processModuleDepsEnd = function(str) {
// Once we have the complete JSON, parse and store it
// for future use
moduleDepsJSON = JSON.parse(moduleDepsJSONStr);
};
var processBundleStr = function(data) {
// store the bundle output until the stream
// is completely processed
bundleStr += data;
};
// Let's keep the bundle creation in a separate function
// which will come in handy when we invoke this whenever
// a file changes
var processFiles = function(callback) {
// invoke module-deps by passing in the entry point file
md = mdeps();
moduleDepsJSONStr = '';
bundleStr = '';
md.pipe(JSONStream.stringify())
.on('data', processModuleDepsStr)
.on('end', processModuleDepsEnd)
.pipe(browserPack())
.on('data', processBundleStr)
.on('end', function() {
fs.writeFile('dist/bundle.js', bundleStr, 'utf8', function() {
console.log('Bundle file written...');
});
});
md.end({ file: path.join(__dirname, args[0]) });
};
// Call the function to create the bundle
processFiles();
// configure express to serve contents of 'dist' folder
app.use('/', express.static('dist'));
// serve the app
http.listen(3001, function(){
console.log('Serving dist on *:3001');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment