[英]Conditionally require modules in javascript
I'm entering the conditional as expected (as proven by a console that is only hit in the if statement if process.env.BROWSER === true
, but the require inside the if statement is still getting hit nomatter if process.env.BROWSER === true
or process.env.BROWSER === false
and this is causing and error when process.env.BROWSER === false
. If I comment out the first require, then when process.env.BROWSER === false
there is no error. 我正在按预期输入条件(如仅在if语句if process.env.BROWSER === true
命中的控制台所证明的那样,但if语句中的require在process.env.BROWSER === true
仍然命中process.env.BROWSER === true
或process.env.BROWSER === false
,这是在process.env.BROWSER === false
时引起的错误,如果我注释掉第一个要求,那么当process.env.BROWSER === false
没有错误。
I suspect that all requires are somehow called when JS is compiling, but if that's the case how can I conditionally require a module? 我怀疑在JS编译时会以某种方式调用所有需求,但是如果是这样,我该如何有条件地需要一个模块? What's exactly happening here? 这到底是怎么回事?
if (process.env.BROWSER) {
language['ES'].push(require('promise?global,locale-es-ES!react-intl/locale-data/es'));
} else{
language['ES'].push(function () {
return Promise.resolve(require('react-intl/locale-data/es'));
});
}
using module.require like this works in react-native but throws a TypeError: module.require is not a function
when in the Browser 像这样使用module.require可以在react-native中工作,但会引发TypeError: module.require is not a function
当在浏览器中时TypeError: module.require is not a function
if (process.env.BROWSER) {
language['ES'].push(module.require('promise?global,locale-es-ES!react-intl/locale-data/es'));
} else{
language['ES'].push(function () {
return Promise.resolve(require('react-intl/locale-data/es'));
});
}
trying to find a reference to module like this gives the TypeError: Cannot read property 'require' of undefined
试图找到对这样的模块的引用给出TypeError: Cannot read property 'require' of undefined
if (process.env.BROWSER) {
language['ES'].push(require('react-intl').module.require('promise?global,locale-es-ES!react-intl/locale-data/es'));
} else{
language['ES'].push(function () {
return Promise.resolve(require('react-intl/locale-data/es'));
});
}
I had faced same problem as above but with nodejs and react native. 我遇到了与上述相同的问题,但是使用了nodejs并做出了本机反应。
I overcame the problem by using module.require()
for nodejs module. 我通过对nodejs模块使用module.require()
克服了这个问题。 Try if you can do this in your case(Or any way to avoid a direct require
for browser case). 请尝试是否可以根据自己的情况进行操作(或采取任何避免直接require
浏览器使用的方式)。
React native would not allow conditional require, and I think does a static analysis loading all require before. React native不允许有条件的需求,我认为之前进行静态分析加载都需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.