You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Using dynamic require on node targets WITHOUT resolve or bundle the target module #4175
This ends up that webpack try to bundle all files which could be the dependencies (forget the name of this - but I'm sure you know what I mean). If the require have just a variable as param logically it just tries to bundle every file... however that's not the point.
put the target file in externals config key does not work because dynamic requires are not tested there
ContextReplacementPlugin does not help here, I don't want to rewrite the module request, I want to AVOID it entirely.
IgnorePlugin etc. will never reached, it's a dynamic import
What is the expected behavior?
Make it possible to just avoid webpack to touch a particular require statement and NOT try to resolve it. This is of course only usable for node builds.
PS
I don't want to use any require.ensure, System.import etc. - forget the name of all 5.
There must be a sync way to require a file on node side, without promises.
Possible solutions:
I don't think it's a good idea for a sixth require method but just to mention, there should be possible something like const server = nodeRequire(entryPath)
What could be possible:
A plugin which receive the require parameter as string maybe? However this seems like like crap solution, too.
Any other ideas?
Reacted by futpib, Gavin H, Gabriele Tomberli, Artem Nechunaev, Almog Hagbi, Andy Wermke, Clement Allen, Jaid, liqiang, akhrabrov and 8 more
Reacted by Egor Voronov, vandalouze, Jason Pearson, away, quophyie, Jakub Buriánek, Vinicius Pacheco, Dmitriy Pushkov, Nemanja Stojanovic, Ovidiu Barabula and 48 more
Reacted by futpib, Hossein Saniei, Domi and vgermes
Reacted by Dimitar Tachev, Georgios Giannoutsos Barkas, Alexey and John Marvin Doniña
Reacted by Vinicius Pacheco, Arkadiusz Czekajski, Kevin BALINI, Vadorequest, Jaid, Georgios Giannoutsos Barkas, ssupinsky, Nathaniel Chen and John Marvin Doniña
I'd like to report a situation I encountered related to this.
I had code depending on [email protected] package, which has code that targets both browser-env and node-env sitting side-by-side in a if ... else ... in one file socket.io-client/lib/io.js.
webpack@v2 seems to have trouble to avoid touching the require in node-env part. It throws: Module not found: Error: Can't resolve 'fs' in './node_modules/socket.io-client/bin'
I just got aware of this when upgrading from webpack@v1. Curiously, v1 never reported this error at bundling this file.
@sokra is there another solution if the require call is in a 3rd party node module, and you can't change it to __non_webpack_require__ ?
In my case, my code requires a node module, which in turn makes a dynamic call to require a file that is user-generated, and present on disk outside of the webpack bundle. When bundling the node module, it rewrite its dynamic require call from:
try {
mod = require(path.join(dir, file)); // where `dir` and `file` are dynamic values
}
catch (err) {
reject(err);
}
to
try {
mod = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
}
catch (err) {
return reject(err);
}
Reacted by Dmitriy Pushkov, atravindra, Nemanja Stojanovic, Paul Li, Ilya Shmelev, Mike Souza, bohendo, Wei Wang, Jesse Thomson, Antonio Stoilkov and 8 more
I'm using Webpack to create deployment builds for NodeJS environments and also came across the need to handle dynamic requires outside of Webpack.
I wanted our codebase to work both pre-webpack and post-webpack, hence I didn't want to introduce __non_webpack_require__ into our codebase.
Our hack:
function requireDynamically(path)
{
path = path.split('\\').join('/'); // Normalize windows slashes
return eval(`require('${path}');`); // Ensure Webpack does not analyze the require statement
}
const path = require('path');
const fs = require('fs');
const files = fs.readdirSync(__dirname);
const moduleName = path.join(__dirname, files[0]);
const foo = requireDynamically(moduleName); // Will be skipped by Webpack
Reacted by Yan Yurkin, akhrabrov, Walt Woods, Ernad Husremović, Evandro Antônio da Costa de Paula, Carl Johnson, Yonah Ochieng, Gabriel Nogueira, Luke Hatcher, ByungJoon Lee and 3 more
Reacted by DooYong Kim
Reacted by Yonah Ochieng, Gabriel Nogueira and DooYong Kim
So I'm assuming that the lack of a response to @olivoil means webpack is not supposed to be able to handle situations where our code imports a 3rd party module which uses dynamic require statements.
There's a noParse module option that prevents WebPack from parsing certain files.. but it explicitly says we shouldn't noParse modules that require or import. Well, if we ignore this suggestion then we might have ourselves a work around.
For example, if you want to webpack code that depends on web3.js, you've probably had trouble with scrypt. A hacky solution:
constpath=require('path');constCopyWebpackPlugin=require('copy-webpack-plugin')module.exports={target: 'node',mode: "development",entry: ['./src/entry.js'],output: {path: path.join(__dirname,'dist'),filename: 'bundle.js',},// These are required by random web3.js dependencies but are not needed, ignore themexternals: ['electron','pg-native'],module: {// This will leave all require statements in this file untouched// Luckily, the scrypt index file only imports node externals (os and crypto)// and the one problematic file. If it imported anything else, this wouldn't worknoParse: [/scrypt\/index.js$/],},plugins: [// We'll manually copy the problematic file to the location where it's expected// Now, when transporting the bundle we also need to keep track of this other filenewCopyWebpackPlugin([{from: '../../node_modules/scrypt/build/Release/scrypt.node',to: './build/Release/scrypt.node',},]),],};
This hacky solution only works because we get lucky & don't import anything else important in the file that imports the problematic file. So by ignoring it entirely, the problematic require is left untouched & the other requires can stand on their own.
Please tell me I'm overthinking this & that there's a simpler way. This seems like such a common situation & I don't understand why WebPack can't handle it more cleanly..
I have another situation where a 3rd party module does these silly dynamic requirements in a file that also requires other important stuff so this hack doesn't work. Seems like my only options are to
Not use this 3rd party module
Modify 3rd party code in node_modules
Abandon webpack
Since 1 isn't an option and 2 is unthinkable, it looks like I'm stuck with option 3..
Reacted by Sidney Nemzer, Akuukis, Minseok Yang, Carl Johnson, José Cabo and Manuel Guerrero
Not the greatest solution, but I was having this same problem using knex migrations in lambdas. This solution seems better than most although still not great.
In your webpack module.rules:
{// regex for the files that are problematictest: /knex\/lib\/migrate\/sources/,loader: 'string-replace-loader',options: {// match a require function call where the argument isn't a string// also capture the first character of the args so we can ignore it latersearch: 'require[(]([^\'"])',// replace the 'require(' with a '__non_webpack_require__(', meaning it will require the files at runtime// $1 grabs the first capture group from the regex, the one character we matched and don't want to losereplace: '__non_webpack_require__($1',flags: 'g'}}
Reacted by Walter Rumsby, ldstein, Jonas Andersson Hultgren, Rémi Jarasson, madagon, Murad, Takuya Matsuyama, TomHermanSAP, Azuka Okuleye, Domi and 9 more
I hope the following hack is helpful for somebody. I tried to achieve the same from a UMD library. My scenario is the following. I have a main React web application bundled with Webpack and a microfrontend UMD library (also in React and bundled with Rollup) which should load in one of the views of the main app from a remote url. Both projects use a lot of the same libraries (react, react-dom, react-bootstrap, etc.) so I didn't want to bundle them in two places. I wanted the library to dynamically import its dependencies if they exist in the bundle of the main application. After 3-4 days of trying all kinds of webpack and rollup configurations (externals etc.) I had to resort to the following ugliness. In the main application I created a function called "remoteImport" and when the UMD module loads I pass the function to the component inside it as a prop. The function looks like this:
const remoteImport = module => {
const str = `./node_modules/${module}`;
// __webpack_require__.c is the cache of already imported node_modules exposed by webpack
const installedModules = __webpack_require__.c;
for(const moduleId of Object.keys(installedModules)) {
if(moduleId.indexOf(str) > -1) {
return __webpack_require__(moduleId);
}
}
return null;
};
Then the UMD library can call remoteImport("react") for example and if it is found in the webpack bundle it will be returned.
Currently @mjewell 's workaround seems to be the best, while certainly still having a lot of issues.
As it stands, Webpack just does not support regular dynamic require. It just bugs out, unless you manually replace require with __non_webpack_require, which is a nonsensical requirement in Node (however makes sense traditionally when Webpack was only targeting the brower).
However, a fix would be great. When will it be possible...
to override the require behavior dynamically?
or at least provide some way of resolving require calls with dynamic arguments?
or at least have __webpack_require__ be respectful of externals, which (just like many other features) are just entirely ignored as soon as we encounter a dynamic require.
-> If we can fix this, that would also take care of the cryptic Critical dependency: the request of a dependency is an expression problem (which is a webpack warning seen for dynamic require calls).
Improved Workaround
For anyone still struggling I took @mjewell's workaround and added some logging.
The biggest downside: Will stop working if your code contains any string that contains the literal require(.
Code:
/** * Gets the line at given offset in s, as well as `nLines` lines below and above. */functiongetLinesAroundOffset(s,offset,nLines=1,maxChars=50){letstart=offset-1;for(leti=0;i<nLines;++i){constnewIdx=s.lastIndexOf('\n',start)-1;if(Math.abs(start-newIdx)>200){// probably compressed codestart-=maxChars;break;}if(newIdx>=0){start=newIdx;}}letend=offset+1;for(leti=0;i<=nLines;++i){constnewIdx=s.indexOf('\n',end)+1;if(Math.abs(end-newIdx)>200){// probably compressed codeend+=maxChars;break;}if(newIdx>=0){end=newIdx;}}returns.substring(start,end);}/** * @see https://github.com/webpack/webpack/issues/4175#issuecomment-695767880 */constdynamicRequireRule={test: /\.js$/,loader: 'string-replace-loader',enforce: 'pre',options: {// match a require function call where the argument isn't a string literalsearch: /require\(\s*(?![\'"])/,// replace the 'require(' with a '__non_webpack_require__(', meaning it will require the files at runtime// $1 grabs the first capture group from the regex, the one character we matched and don't want to lose// replace: '__non_webpack_require__($1',// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameterreplace: (match,offset,s)=>{// debugger;constrequireLines=getLinesAroundOffset(s,offset,1);// eslint-disable-next-line no-consoleconsole.warn(`Fixing dynamic require:\n`,/* match */requireLines,'\n\n');return`__non_webpack_require__(`;},flags: 'g'}};// ...
module: {rules: [dynamicRequireRule]}
I know many of you think it's fine to eval() if you know what's going into it, but it's always good to reiterate the point that you shouldn't eval anything that can be user generated. If this were determined by a url, a simple url change could trigger a script injection like so: requireDynamically('some-package.js\');alert("Script injected!");\/\/')
For anyone, using some third-party modules that use dynamic require like migration package and looking for a solution, you can use the following plugin.
function requireDynamically(path)
{
path = path.split('\').join('/'); // Normalize windows slashes
return eval(require('${path}');); // Ensure Webpack does not analyze the require statement
}
would be better written this way
// Ensure Webpack does not analyze the require statementconstrequireDynamically=eval('require');
This way you're guaranteed not to eval any dynamic content and only have to execute the eval once on module load. (In fact i think we can leave out the windows slash normalization potentially as well.. edited to reflect that)
The magic comment didn't work for me in weback 5 to avoid the warning about dynamic dependencies so I resort to my first ever use of eval.. cue tears..
Activity
sokra commentedon Feb 3, 2017
const server = __non_webpack_require__(entryPath)hackape commentedon Feb 21, 2017
I'd like to report a situation I encountered related to this.
I had code depending on
[email protected]package, which has code that targets both browser-env and node-env sitting side-by-side in aif ... else ...in one file socket.io-client/lib/io.js.webpack@v2seems to have trouble to avoid touching therequirein node-env part. It throws:Module not found: Error: Can't resolve 'fs' in './node_modules/socket.io-client/bin'I just got aware of this when upgrading from
webpack@v1. Curiously, v1 never reported this error at bundling this file.hackape commentedon Feb 21, 2017
I just digged into the built result of
webpack@v1, it dumps the unwanted node-env-targeted if block entirely!olivoil commentedon Apr 1, 2017
@sokra is there another solution if the
requirecall is in a 3rd party node module, and you can't change it to__non_webpack_require__?In my case, my code requires a node module, which in turn makes a dynamic call to
requirea file that is user-generated, and present on disk outside of the webpack bundle. When bundling the node module, it rewrite its dynamicrequirecall from:to
ldstein commentedon Aug 17, 2017
I'm using Webpack to create deployment builds for NodeJS environments and also came across the need to handle dynamic requires outside of Webpack.
I wanted our codebase to work both pre-webpack and post-webpack, hence I didn't want to introduce
__non_webpack_require__into our codebase.Our hack:
RoboPhred commentedon Nov 8, 2017
A simpler way to pull this off without resorting to eval is:
In the bundled output, this will become
This will work, as webpack uses
__webpack_require__, and leavesrequireas the original node function.(Note: Currently this will not work if the typeof targets
__non_webpack_require__. See #5939)webpack-bot commentedon Aug 31, 2018
This issue had no activity for at least half a year.
It's subject to automatic issue closing if there is no activity in the next 15 days.
mholtzhausen commentedon Sep 4, 2018
I'm sure this could be written better - but my prototype solution is:
One can then use this function instead of regular require
dRequire('/bla/somefile.js')Don't yell at me for
eval, if you're going to dynamically add a file to your source, you had better be sure it contains safe stuffbohendo commentedon Sep 19, 2018
So I'm assuming that the lack of a response to @olivoil means webpack is not supposed to be able to handle situations where our code imports a 3rd party module which uses dynamic require statements.
There's a noParse module option that prevents WebPack from parsing certain files.. but it explicitly says we shouldn't
noParsemodules that require or import. Well, if we ignore this suggestion then we might have ourselves a work around.For example, if you want to webpack code that depends on web3.js, you've probably had trouble with
scrypt. A hacky solution:This hacky solution only works because we get lucky & don't import anything else important in the file that imports the problematic file. So by ignoring it entirely, the problematic
requireis left untouched & the other requires can stand on their own.Please tell me I'm overthinking this & that there's a simpler way. This seems like such a common situation & I don't understand why WebPack can't handle it more cleanly..
I have another situation where a 3rd party module does these silly dynamic requirements in a file that also requires other important stuff so this hack doesn't work. Seems like my only options are to
Since 1 isn't an option and 2 is unthinkable, it looks like I'm stuck with option 3..
mjewell commentedon Jan 1, 2019
Not the greatest solution, but I was having this same problem using knex migrations in lambdas. This solution seems better than most although still not great.
In your webpack
module.rules:also you will need to install string-replace-loader: https://github.com/Va1/string-replace-loader
Fixing dynamic require missing from webpack
2 remaining items
Fixing dynamic require missing from webpack
Fixing dynamic require missing from webpack (#6908)
josiahruddell commentedon Feb 6, 2019
I was able to work around the issue by using webpack's
noParsemodule configuration. I posted the solution on stack overflow.nzvtrk commentedon May 28, 2019
i found the same problem with async imports on win32.
Wrong code:
After change slashes in webpackInclude regexp, everything is ok.
webpackInclude: /features\\[^\/]+\\src\\index\.js/alex-vukov commentedon Feb 12, 2020
I hope the following hack is helpful for somebody. I tried to achieve the same from a UMD library. My scenario is the following. I have a main React web application bundled with Webpack and a microfrontend UMD library (also in React and bundled with Rollup) which should load in one of the views of the main app from a remote url. Both projects use a lot of the same libraries (react, react-dom, react-bootstrap, etc.) so I didn't want to bundle them in two places. I wanted the library to dynamically import its dependencies if they exist in the bundle of the main application. After 3-4 days of trying all kinds of webpack and rollup configurations (externals etc.) I had to resort to the following ugliness. In the main application I created a function called "remoteImport" and when the UMD module loads I pass the function to the component inside it as a prop. The function looks like this:
Then the UMD library can call remoteImport("react") for example and if it is found in the webpack bundle it will be returned.
Domiii commentedon Sep 20, 2020
Currently @mjewell 's workaround seems to be the best, while certainly still having a lot of issues.
As it stands, Webpack just does not support regular dynamic
require. It just bugs out, unless you manually replacerequirewith__non_webpack_require, which is a nonsensical requirement in Node (however makes sense traditionally when Webpack was only targeting the brower).However, a fix would be great. When will it be possible...
requirebehavior dynamically?__webpack_require__be respectful ofexternals, which (just like many other features) are just entirely ignored as soon as we encounter a dynamic require.-> If we can fix this, that would also take care of the cryptic
Critical dependency: the request of a dependency is an expressionproblem (which is a webpack warning seen for dynamicrequirecalls).Improved Workaround
For anyone still struggling I took @mjewell's workaround and added some logging.
The biggest downside: Will stop working if your code contains any string that contains the literal
require(.Code:
webpack-bot commentedon Jan 16, 2021
This issue had no activity for at least three months.
It's subject to automatic issue closing if there is no activity in the next 15 days.
webpack-bot commentedon Jan 31, 2021
Issue was closed because of inactivity.
If you think this is still a valid issue, please file a new issue with additional information.
alexander-akait commentedon Feb 1, 2021
webpack@5 supports magic comments for
require#11316, so you can avoid using__non_webpack_require__, example:webpack.config.js
node.js
So, I think it can be closed, sorry for delay and feel free to feedback
yonahochieng commentedon Apr 16, 2021
Thank you ... saved me big time
adjenks commentedon Apr 16, 2021
I know many of you think it's fine to
eval()if you know what's going into it, but it's always good to reiterate the point that you shouldn't eval anything that can be user generated. If this were determined by a url, a simple url change could trigger a script injection like so:requireDynamically('some-package.js\');alert("Script injected!");\/\/')hle-aashish commentedon May 20, 2021
For anyone, using some third-party modules that use dynamic
requirelike migration package and looking for a solution, you can use the following plugin.https://framagit.org/Glandos/webpack-ignore-dynamic-require
scamden commentedon May 21, 2021
would be better written this way
This way you're guaranteed not to eval any dynamic content and only have to execute the eval once on module load. (In fact i think we can leave out the windows slash normalization potentially as well.. edited to reflect that)
The magic comment didn't work for me in weback 5 to avoid the warning about dynamic dependencies so I resort to my first ever use of eval.. cue tears..