├── .gitignore ├── README.md ├── index.js ├── makeIdentitySourceMap.js ├── package.json └── patcher.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # monkey-hot-loader 3 | 4 | A [webpack](http://webpack.github.io/docs/) loader which adds live 5 | updating functionality to a JavaScript system. View 6 | [this post](http://jlongster.com/Backend-Apps-with-Webpack--Part-III) 7 | for gory technical details. 8 | 9 | ## Summary 10 | 11 | This loader acts similarly to 12 | [react-hot-loader](http://gaearon.github.io/react-hot-loader/) in that 13 | it uses webpack's HMR infrastructure to be notified when a module has 14 | changed. When it changes, it takes the new module's code and 15 | monkey-patches the live running system automatically, so all you have 16 | to do is **edit a file and save it**. 17 | 18 | As described in 19 | [my post](http://jlongster.com/Backend-Apps-with-Webpack--Part-III), 20 | currently this only supports updating top-level functions in a module. 21 | That means given this code: 22 | 23 | ```js 24 | function foo() { 25 | return 5; 26 | } 27 | 28 | function bar() { 29 | return function() { 30 | // ... 31 | } 32 | } 33 | 34 | module.exports = function() { 35 | // ... 36 | } 37 | ``` 38 | 39 | only `foo` and `bar` will update in the live system when changed. 40 | Editing the function within `bar` will reload `bar` entirely; we have 41 | no support for patching arbitrary functions like closures. 42 | 43 | Turns out this is still incredibly valuable, and much easier to 44 | rationalize about. 45 | 46 | In the future, this could patch methods on classes as well which would 47 | cover the majority of JavaScript code. 48 | 49 | ## Usage 50 | 51 | See [the gulpfile](https://github.com/jlongster/backend-with-webpack/blob/master/gulpfile.js) in `backend-with-webpack` to see a full setup. This is a bit confusing right now. If you check out [backend-with-webpack](https://github.com/jlongster/backend-with-webpack), run `npm install` and `gulp run` you should have a full setup running. 52 | 53 | 1- Install the loader 54 | 55 | ``` 56 | npm install monkey-hot-loader 57 | ``` 58 | 59 | 2- Add the loader to your webpack config, for example: 60 | 61 | ```js 62 | module: { 63 | loaders: [ 64 | {test: /\.js$/, exclude: /node_modules/, loaders: ['monkey-hot', 'babel'] }, 65 | ] 66 | } 67 | ``` 68 | 69 | 3a- For the frontend, you need to run the [Webpack Dev Server](http://webpack.github.io/docs/webpack-dev-server.html) to serve your assets. It will create a socketio server that your frontend uses to receive notifications. You can see an example of using the API in react-hot-loader's [same code](https://github.com/gaearon/react-hot-boilerplate/blob/master/server.js) to fire up the server. Make sure to load your assets from this server (i.e. `http://localhost:3000/js/bundle.js`). 70 | 71 | 3b- In your webpack config, add 2 more files to load, which connect and listen to the dev server. Additionally, add the `HotModuleReplacementPlugin` to plugins. 72 | 73 | Make sure that the adress & port of the webpack-dev-serve query points to the dev server instance. 74 | 75 | ```js 76 | var frontendConfig = config({ 77 | entry: [ 78 | 'webpack-dev-server/client?http://localhost:3000', 79 | 'webpack/hot/only-dev-server', 80 | './static/js/main.js' 81 | ], 82 | output: { 83 | ... 84 | }, 85 | plugins: [ 86 | new webpack.HotModuleReplacementPlugin() 87 | ] 88 | }); 89 | ``` 90 | 91 | 4a- For the backend, do the same as the frontend except add only `webpack/hot/signal.js` file to your entry point. Also make sure to give a path to `recordsPath`. 92 | 93 | ```js 94 | var backendConfig = config({ 95 | entry: [ 96 | 'webpack/hot/signal.js', 97 | './src/main.js' 98 | ], 99 | target: 'node', 100 | output: { 101 | ... 102 | }, 103 | recordsPath: path.join(__dirname, 'build/_records'), 104 | plugins: [ 105 | new webpack.HotModuleReplacementPlugin() 106 | ] 107 | }); 108 | ``` 109 | 110 | The `signal.js` file instruments your app to check for updates when it receives a SIGURS2 signal. This is the same signal that nodemon uses to signal a restart, but `signal.js` overrides this behavior. Instead of restarting, your app will simply patch itself. 111 | 112 | 4b- For now, this setup requires nodemon, but in the future there could be multiple ways to talk to your running app. If you are using gulp, start your app with nodemon like this: 113 | 114 | ```js 115 | nodemon({ 116 | execMap: { 117 | js: 'node' 118 | }, 119 | script: path.join(__dirname, 'build/backend'), 120 | ignore: ['*'], 121 | watch: ['nothing/'], 122 | ext: 'noop' 123 | }); 124 | ``` 125 | 126 | We tell `nodemon` to watch no files, since we don't care about that. 127 | 128 | 4c- Now, when webpack is done running, call `nodemon.restart()`. You will need to call webpack via that API. You should probably be doing all of this through gulp anyway. 129 | 130 | ```js 131 | webpack(backendConfig).watch(100, function(err, stats) { 132 | nodemon.restart(); 133 | }); 134 | ``` 135 | 136 | I know it's confusing, but remember, this restart just sends the signal which our app captures and actually just does an update. 137 | 138 | I recommend just checking out [backend-with-webpack](https://github.com/jlongster/backend-with-webpack), installing with `npm install` and running with `gulp run` and playing with it there. 139 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var fs = require('fs'); 3 | var path = require('path'); 4 | var SourceNode = require('source-map').SourceNode; 5 | var SourceMapConsumer = require('source-map').SourceMapConsumer; 6 | var acorn = require('acorn'); 7 | var makeIdentitySourceMap = require('./makeIdentitySourceMap'); 8 | 9 | var patcherCode = fs.readFileSync(path.join(__dirname, 'patcher.js'), 'utf8'); 10 | 11 | module.exports = function(source, map) { 12 | if(this.cacheable) { 13 | this.cacheable() 14 | } 15 | 16 | var ast = acorn.parse(source); 17 | var names = ast.body 18 | .filter(function(node) { return node.type === 'FunctionDeclaration'; }) 19 | .map(function(node) { return node.id.name; }); 20 | 21 | var appendText = [ 22 | '/* HOT PATCH LOADER */', 23 | 'var __moduleBindings = ' + JSON.stringify(names) + ';', 24 | patcherCode 25 | ].join(' '); 26 | 27 | if(this.sourceMap === false) { 28 | return this.callback(null, [source, appendText]); 29 | } 30 | 31 | if(!map) { 32 | map = makeIdentitySourceMap(source, this.resourcePath); 33 | } 34 | 35 | var node = new SourceNode(null, null, null, [ 36 | SourceNode.fromStringWithSourceMap(source, new SourceMapConsumer(map)), 37 | new SourceNode(null, null, this.resourcePath, appendText) 38 | ]).join('\n\n'); 39 | 40 | var result = node.toStringWithSourceMap(); 41 | this.callback(null, result.code, result.map.toString()); 42 | } 43 | -------------------------------------------------------------------------------- /makeIdentitySourceMap.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var SourceMapGenerator = require('source-map').SourceMapGenerator; 4 | 5 | function makeIdentitySourceMap(content, resourcePath) { 6 | var map = new SourceMapGenerator(); 7 | map.setSourceContent(resourcePath, content); 8 | 9 | content.split('\n').map(function (line, index) { 10 | map.addMapping({ 11 | source: resourcePath, 12 | original: { 13 | line: index + 1, 14 | column: 0 15 | }, 16 | generated: { 17 | line: index + 1, 18 | column: 0 19 | } 20 | }); 21 | }); 22 | 23 | return map.toJSON(); 24 | } 25 | 26 | module.exports = makeIdentitySourceMap; 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "monkey-hot-loader", 3 | "description": "A webpack loader which adds live updating functionality", 4 | "version": "0.0.3", 5 | "author": "James Long ", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/jlongster/monkey-hot-loader.git" 9 | }, 10 | "dependencies": { 11 | "acorn": "^0.12.0", 12 | "source-map": "^0.4.2" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /patcher.js: -------------------------------------------------------------------------------- 1 | if(module.hot) { 2 | module.hot.accept(function(err) { 3 | console.log('[HMR] Error accepting: ' + err); 4 | }); 5 | 6 | var getEvalSource = function(func) { 7 | var code = func.toString(); 8 | var m = code.match(/^function\s+__eval\s*\((.*)\)\s*\{([\s\S]*)\}$/i); 9 | if(!m) { 10 | return null; 11 | } 12 | var args = m[1]; 13 | var body = m[2]; 14 | var scope = {}; 15 | 16 | if(args.trim()) { 17 | args.split(',').forEach(function(arg) { 18 | if(arg.indexOf('=') !== -1) { 19 | var p = arg.split('='); 20 | scope[p[0].trim()] = JSON.parse(p[1]); 21 | } 22 | else { 23 | scope[arg.trim()] = undefined; 24 | } 25 | }); 26 | } 27 | 28 | return { body: body, scope: scope }; 29 | } 30 | 31 | var injectScope = function(scope, code) { 32 | // Take an explicit scope object and inject it so that 33 | // `code` runs in context of it 34 | var injected = Object.keys(scope).map(function(binding) { 35 | return 'var ' + binding + ' = evalScope.' + binding + ';' 36 | }).join(' '); 37 | 38 | // Update our scope object with any modifications 39 | var extracted = Object.keys(scope).map(function(binding) { 40 | return 'evalScope.' + binding + ' = ' + binding + ';'; 41 | }).join(' '); 42 | 43 | return injected + code + extracted; 44 | } 45 | 46 | var bindings = __moduleBindings; 47 | 48 | if(!module.hot.data) { 49 | // First time loading. Try and patch something. 50 | var patchedBindings = {}; 51 | var evalScope = {}; 52 | 53 | var moduleEvalWithScope = function(frame) { 54 | // Update the scope to reflect only the values specified as 55 | // arguments to the __eval function. Copy over values from the 56 | // existing scope and ignore the rest. 57 | Object.keys(evalScope).forEach(function(arg) { 58 | if(arg in frame.scope) { 59 | frame.scope[arg] = evalScope[arg]; 60 | } 61 | }); 62 | evalScope = frame.scope; 63 | 64 | var code = injectScope(evalScope, frame.body); 65 | return eval(code); 66 | } 67 | 68 | var moduleEval = function(code) { 69 | return eval(code); 70 | } 71 | 72 | bindings.forEach(function(binding) { 73 | var f = eval(binding); 74 | 75 | if(typeof f === 'function' && binding !== '__eval') { 76 | var patched = function() { 77 | if(patchedBindings[binding]) { 78 | return patchedBindings[binding].apply(this, arguments); 79 | } 80 | else { 81 | return f.apply(this, arguments); 82 | } 83 | }; 84 | patched.prototype = f.prototype; 85 | 86 | eval(binding + ' = patched;\n'); 87 | 88 | if(module.exports[binding]) { 89 | module.exports[binding] = patched; 90 | } 91 | } 92 | }); 93 | 94 | module.hot.dispose(function(data) { 95 | data.patchedBindings = patchedBindings; 96 | data.moduleEval = moduleEval; 97 | data.moduleEvalWithScope = moduleEvalWithScope; 98 | }); 99 | } 100 | else { 101 | var patchedBindings = module.hot.data.patchedBindings; 102 | 103 | bindings.forEach(function(binding) { 104 | var f = eval(binding); 105 | 106 | if(typeof f === 'function' && binding !== '__eval') { 107 | // We need to reify the function in the original module so 108 | // it references any of the original state. Strip the name 109 | // and simply eval it. 110 | var funcCode = ( 111 | '(' + f.toString().replace(/^function \w+\(/, 'function (') + ')' 112 | ); 113 | patchedBindings[binding] = module.hot.data.moduleEval(funcCode); 114 | } 115 | }); 116 | 117 | if(typeof __eval === 'function') { 118 | try { 119 | module.hot.data.moduleEvalWithScope(getEvalSource(__eval)); 120 | } 121 | catch(e) { 122 | console.log('error evaling: ' + e); 123 | } 124 | } 125 | 126 | module.hot.dispose(function(data) { 127 | data.patchedBindings = patchedBindings; 128 | data.moduleEval = module.hot.data.moduleEval; 129 | data.moduleEvalWithScope = module.hot.data.moduleEvalWithScope; 130 | }); 131 | } 132 | } 133 | --------------------------------------------------------------------------------