Webpack implements hot replacement of Node. js code and webpacknode. js

Source: Internet
Author: User

Webpack implements hot replacement of Node. js code and webpacknode. js

Gitter asked this question over the past two days, asked on Twitter, and asked on GitHub, but did not respond in the past two days.
I didn't know the contact information of the author of Webpack because the jlongster who wrote the blog ignores me.
The last message sent to Gitter seemed to have been seen, and he roughly explained it again...
Https://github.com/webpack/docs/issues/45#issuecomment-149793458

Here is the process in short:Compile the server code with webpackUse target: "node" or target: "async-node"Enabled HMR via --hot or HotModuleReplacementPluginUse webpack/hot/poll or webpack/hot/signalThe first polls the fs for updates (easy to use)The second listens for a process event to check for updates (you need a way to send the signal)Run the bundle with node.You can't use existing HMR loaders like react-hot-loader or style-loader because they make no sense in a server environment. Just add manuall replacement code at the correct location (i. e. accept request handler like in the example)You can't use the webpack-dev-server. It's a server which serves assets not a runner. Just run webpack --watch and node bundle.js. I would go the webpack/hot/poll?1000 route first. It's pretty easy to use and suitable for dev environments. For production (if you want to hot update your production server) the signal approach is better suited.

The original words are not translated. After understanding it, it mainly involves how to configure Webpack and how to run the script.
I wrote it once, and the code is only so short that hot replacement is implemented:
Https://github.com/jiyinyiyong/webpack-backend-HMR-demo
The code can be copied from the jlongster configuration Tutorial:
Http://jlongster.com/Backend-Apps-with-Webpack--Part-II

Webpack = require 'webpackage' module. exports = entry: ['webpack/hot/poll? 1000 '# <-- poll the updated content code '. /src/main' # <-- project entry] target: 'node' # <-- indicates that the compilation method is node output: path: 'build/'filename: 'bundle. js' # <-- file name module of the compilation result: loaders: [{test :/\. coffee/, loader: 'coffee '}] plugins: [new webpack. hotModuleReplacementPlugin () # <-- start hot mode as usual] resolve: extensions :['. js ','','. coffee ']

When running in the command line environment, pay attention to webpack instead of webpack-dev-server.
Note that the backend is running & just to avoid blocking. If you have two terminals, open two.

Npm iwebpack -- watch & # <-- watch mode node build/bundle. js # <-- runs the code for packaging results

I wrote two test files. One is the code src/lib. coffee that will be modified:

exports.data = 'code 5'exports.printSelf = -> console.log 'doing 3'

Another entry file src/main. coffee contains the code for replacing the processing module:

lib = require './lib'console.log lib.datalib.printSelf()counter = 0setInterval -> counter += 1 console.log counter, 2000if module.hot module.hot.accept './lib', ->  lib = require './lib'  console.log lib.data  lib.printSelf()

Once you run the Demo, you will know how it works. setInterval is not affected by the replacement.
In the build/directory, each modification generates a JSON file to record the modified content:

Copy codeThe Code is as follows: Compile CMDL build/
Small-update. js 0. Small. hot-update.js 2849b61a15d31ffe5e08. hot-update.json small-update. js 0. eaa7b323eba37ae58997. hot-update.js small. hot-update.json fb584971920454f9ccbe. hot-update.json
0.9abf25005c61357a0ce5.hot-update. js 0. fb584971920454f9ccbe. hot-update.js a664b5851a99ac0865ca. hot-update.json
0.9b4a5ad617ec1dbc48a3.hot-update. js 1dadeb2eb7b01e150126. hot-update.json bundle. js
0. a664b5851a99ac0865ca. hot-update.js 256267122c6d325755b0. hot-update.json c1d0d73de11660806d0c. hot-update.json

The specific file content is like this. It can be considered to include the information required for identification and update:

➤➤ cat build/0.c797c084381bfeac37f7.hot-update.jsexports.id = 0;exports.modules = {/***/ 3:/***/ function(module, exports, __webpack_require__) {  var counter, lib;  lib = __webpack_require__(4);  console.log(lib.data);  lib.printSelf();  counter = 0;  setInterval(function() {   counter += 1;   return console.log(counter, 3);  }, 2000);  if (true) {   module.hot.accept(4, function() {    lib = __webpack_require__(4);    console.log(lib.data);    return lib.printSelf();   });  }/***/ }};

Other solutions

By the way, I posted a post on the forum asking about the solution on the Internet during the day. There are mainly two clear solutions available, which are worth learning from.

One is Baidu's technical blog, which is about how to handle module objects, that is, manually listening for file modifications, then figuring out module caching and re-attaching modules.
The thinking is clear and meticulous. Although there is a bit of redundant code, you can try again:
Http://www.bkjia.com/article/73739.htm

The other seems to be for require. extensions performs hack and adds operations and events. When the module File is updated, the corresponding module is automatically updated, and an emit event is generated, the position referenced by the module can be processed and the new code is used. This should be said to be rude. After all, not all codes are easy to replace.
Https://github.com/rlidwka/node-hotswap

Feelings

Considering that I am already hanging on the Webpack tree, I am not going to study it in depth. Maybe Node. js official lib/module. js optimization can produce good functions. However, JavaScript is not a vulnerable community for immutable data usage. It cannot be compared with Erlang because code replacement involves status update, if this is not the case, it is better to restart the system. However, restart now has three node-dev supervisor nodemon solutions for you.

For me, the Cumulo solution relies heavily on WebSocket. Currently, front-end development can update code on the server and automatically update the client,
Through the Webpack and React mechanisms, the DOM and pure function modules are partially updated. If the development environment can be hot replaced, the development efficiency will be greatly improved, I think hot replacement is out of reach, but it is likely to be at your fingertips to improve efficiency!

There may be pitfalls in the future. After all, black technology...

If you are interested, you can take a closer look at several related works written by jlongster. It is very helpful:
Http://jlongster.com/archive

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.