search
HomeWeb Front-endJS TutorialWebpack implements Node.js code hot replacement_node.js

For the past two days, I have asked about this issue on Gitter, Twitter, and GitHub, but there has been no response for two days
It turns out that the blogger jlongster ignored me, and I didn’t know the contact information of the author of Webpack
He seemed to have seen the last message posted on Gitter, so he roughly explained it. It was so enlightening...
https://github.com/webpack/docs/issues/45#issuecomment-149793458

Here is the process in short:

Compile the server code with webpack
Use target: "node" or target: "async-node"
Enabled HMR via --hot or HotModuleReplacementPlugin
Use webpack/hot/poll or webpack/hot/signal
The 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 will not be translated. After understanding, the main thing is how to configure Webpack and how to run the script
I wrote it again. The code is only so short, and hot replacement is implemented:
https://github.com/jiyinyiyong/webpack-backend-HMR-demo
The code can be copied from jlongster’s configuration tutorial:
http://jlongster.com/Backend-Apps-with-Webpack--Part-II

webpack = require 'webpack'

module.exports =
 entry: [
  'webpack/hot/poll&#63;1000' # <-- 轮询更新内容的代码
  './src/main' # <-- 项目入口
 ]
 target: 'node' # <-- 指明编译方式为 node
 output:
  path: 'build/'
  filename: 'bundle.js' # <-- 编译结果的文件名
 module:
  loaders: [
   {test: /\.coffee/, loader: 'coffee'}
  ]
 plugins: [
  new webpack.HotModuleReplacementPlugin() # <-- 照常启动 hot mode
 ]
 resolve:
  extensions: ['.js', '', '.coffee']

If running in command line environment, please note that it is webpack instead of webpack-dev-server
Pay attention to the & running in the background just to avoid blocking. If you have two terminals, just open two

npm i
webpack --watch & # <-- watch 模式
node build/bundle.js # <-- 运行的是打包结果的代码

I wrote two test files, one is the modified code src/lib.coffee:

exports.data = 'code 5'

exports.printSelf = ->
 console.log 'doing 3'

Another entry file src/main.coffee contains code to handle module replacement:

lib = require './lib'

console.log lib.data
lib.printSelf()

counter = 0
setInterval ->
 counter += 1
 console.log counter
, 2000

if module.hot
 module.hot.accept './lib', ->
  lib = require './lib'

  console.log lib.data
  lib.printSelf()

Run the demo and you will know the effect. setInterval is not affected by substitution
In the build/ directory, each modification will generate a JSON file to record the modified content:

Copy code The code is as follows:
➤➤ l build/
0.1dadeb2eb7b01e150126.hot-update.js 0.c1d0d73de39660806d0c.hot-update.js 2849b61a15d31ffe5e08.hot-update.json 0.99ea3ea7633f6b3750e6.hot-update.js 0.ea a7b323eba37ae58997.hot-update.js 9b4a5ad617ec1dbc48a3.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 c1d0d73de39660806d0c.hot-update.json

The specific file content is like this, which can be roughly considered to contain the information needed to identify updates:

&#10148;&#10148; cat build/0.c797c084381bfeac37f7.hot-update.js
exports.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 plans

I was looking for solutions on the Internet during the day, and posted a post on the forum asking about this matter. There are two main existing solutions with relatively clear explanations, which are worth learning from

One is on Baidu’s technology blog, which probably describes how to process module objects, that is, manually monitor file modifications, then clear the module cache, and remount the module
The ideas are clear and carefully considered. Although the code is a bit redundant, you can still give it a try:
http://www.jb51.net/article/73739.htm

The other one seems to be a hack on require.extensions, adding operations and events. When the module file is updated, the corresponding module is automatically updated, and an event is emitted. Through this effect, the location referenced by the module can be processed. , using new code, this should be said to be relatively crude, after all, not all codes are easy to replace
https://github.com/rlidwka/node-hotswap

Impressions

Considering that I have already hung myself on the Webpack tree, I don’t plan to study it in depth. Maybe Node.js officially optimizes lib/module.js to get good functions. However, JavaScript is not The community where the use of immutable data is popular cannot compare with Erlang, because code replacement involves the problem of status update, which is difficult to do. It is easier to restart, and restart now has three options for you to choose: node-dev supervisor nodemon

For me, the main reason is that the Cumulo solution has a huge dependence on WebSocket. Now front-end development can update the code on the server and the client automatically updates,
Through the mechanisms of Webpack and React, DOM and pure function modules are partially updated. If the development environment can also be hot-replaced, this will greatly improve development efficiency. I originally thought that hot-replacement was out of reach, but it is very possible. It’s an efficiency improvement within reach!

There may be pitfalls behind, after all, black technology... I’ll tell you when you encounter it

If you are interested, you can take a closer look at several related masterpieces written by jlongster, which are very helpful:
http://jlongster.com/archive

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.