module.createRequire webpack bundling

Viewed 354

I am trying to bundle a node application into a single file.

However after inspecting the output of webpack after the bundling.

I found that one of the libraries uses Module.createRequire to load some module at runtime. Inspecting the bundled code I understood that webpack doesn't replace Module.createRequire(path).resolve by __webpack_require__ , which results in my application depending on node_module after being bundled.

I can think of a simple solution by modifying the code of the library and use require instead of Module.createRequire. But I prefer not to modify the library code cause that would add extra headache every time I want to update the library.

Secondly I am wondering if I replaced the following code Module.createRequire(myPath) by require(myPath) according to Webpack Context would webpack bundle all of the node_modules as the resulting expression * would match with all the modules ?

1 Answers

I was mistaken about Module.createRequire(path).resolve. I thought it resolves the module but actually it is just resolving the path.

However what causing the issue is require(path). For webpack that's a bundle without any context, so it generates webpackEmptyContext for it. Which does nothing but throwing an exception.

A hacky solution to go around that is to replace the require in the considered file by __non_webpack_require__ as follows Using dynamic require on node targets WITHOUT resolve or bundle the target module

Of course you would have to copy the modules to the right path as they are not being bundled. You can use webpacCopyPlugin for that.

I am amazed that there is no official documentation concerning that behavior in the following documentation Webpack Context, or anywhere else. And it looks like a scenario that could happen very often especially not having control of the code. I had to figured it out myself, and I hope I am mistaken, and I hope there is a cleaner way to do so.

Related