Ignoring specific require()s in Webpack?

本小妞迷上赌 提交于 2021-02-18 08:01:10

问题


I have a library interoperable with NodeJS and the Browser and both are being run through Webpack to produce the final bundle. The issue I'm running into is Webpack will rewrite all require() statements to __webpack_require__() and try to bundle the library, which doesn't work for things like fs and worker_threads. How do I make it ignore certain require()s and related mechanisms (require.resolve(), import, etc) given a specific input string?

I've read that I can use the webpack.IgnorePlugin but I'd rather not have the user have to add a special rule in their build for my library. I also couldn't get this to work myself, it still rewrote the require()s. I've also read I can do eval('require("fs")') but this seems hacky, but I'm willing to do this if it's really the best way.

Example:

//example.js
if(typeof window !== "undefined") {
    //Browser
    var myWorker = new Worker();
}
else {
    //NodeJS
    var Worker = require("worker_threads"); //I want Webpack to keep this line as-is
    var myWorker = new Worker();
}

回答1:


To keep a require call as-is in your code after bundling with Webpack, simply replace require with __non_webpack_require__. So your example will look like this:

if (typeof window !== "undefined") {
    var myWorker = new Worker();
}
else {
    var Worker = __non_webpack_require__("worker_threads");
    var myWorker = new Worker();
}

This is a hidden feature of Webpack (possibly because it isn't used very often) found here that ignores require calls so they can be evaluated when the app is run instead of when it's bundled.

Note that this shouldn't be used for apps targeting the web browser since it will result in resolve being used, and web browsers don't know what resolve is. Only use it in code that targets Node.



来源:https://stackoverflow.com/questions/52581441/ignoring-specific-requires-in-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!