In WebPack and NodeJS, we often use the require function to load native modules or developer-defined modules.

Native module loading, such as:

Const path = the require (” path “);

This statement is often used in WebPack and NodeJS applications. Today we’ll talk about how it works.

Again, learn through single-step debugging.

You should first go through my previous article how to debug the WebPack packaging process? Learn how to debug the WebPack packaging process.

The realization of the require function in file:///internal/module.js

Notice requireDepth plus or minus one on lines 10 and 13. The requireDepth field is needed to record the depth at which a module is loaded because it is possible to recursively load other dependent modules when a module is loaded via require.

The actual address of module.js is located under the node_modules folder in the current project folder:

What does the mod variable in line 11 represent?

From the debugger, it is the current command line node that launches webpack.js:

Mod.require (path) posts execution to the module. _load function:

Module._cache first checks to see if the path Module is loaded. In my case, path is loaded for the first time, so module. _cache is empty.

Nativemodule.require (filename):

NativeModule, a nativeModule, also has a caching mechanism.

Because the path module is obviously a NativeModule, rather than a developer-defined module, nativemodule.getcached returns the path module that has been preloaded.

Cached. exports contains a set of functions that we use in nodeJS applications, such as join, parse, resolve, and so on.

This is how native modules in NodeJS and WebPack are loaded. Hope to be helpful to front-end developers.

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: