我尝试了很多检查。这绝对是一个异常现象。我有一个 Angular 2 服务加载@type
定义 (typescript 2) 依次加载 common.js 模块 (视觉媒体/调试 https://stackoverflow.com/a/39666118/1903781)。在 common.js 模块内,我有一个简单的 if 语句,即使条件为 false 并且不应执行代码,该语句也会触发错误。 Angular 应用程序使用system.js
加载模块。
常规代码 if (false) { console.log('This code is not executed') }
正常行为,没有任何反应
异常代码: if (false) { exports.humanize = require('ms'); }
它触发Error: zone.js:101 GET http://localhost:8002/ms.js 404 (Not Found)
错误本身是有效的。事实上,这个脚本是找不到的。最大的错误在于它从一开始就不应该出现。它应该被 false if 条件阻止。在我看来,这zone.js
即使情况为假,也会以某种方式解析指令。我可以做什么来避免这种情况?我需要检查是否需要一个路径或另一个路径,具体取决于服务器或前端是否调用相同的脚本。
CJS 模块内部的大图:
// Trying to detect if environment is node.js
// In backend (no zones) everything works as expected
// In frontend, the require('ms') statement is executed event if condition is false.
// I checked manually if process is defined, it's not.
// Event the basic `false` condition also fails to block code.
if (typeof process === 'undefined') {
exports.humanize = require('node_modules/ms/index.js');
console.log('Browser');
} else {
exports.humanize = require('ms'); // If I comment this code works as intended
console.log('Node');
}
你用systemjs吗?我在多行注释块中的导入语句中遇到了类似的情况。 SystemJS 使用正则表达式来检测 import 语句。也许它使用相同的方法来检测导出语句。
这在 zone.js 中不是问题,因为 zonejs 只是执行任务。任务本身是在其他地方触发的。
编辑(评论的答案):
我认为您不应该有条件地执行导出语句。
也许这有帮助:
var myExport;
var myRequired;
if (something) {
myExport = function() {
console.log('exported this');
};
myRequired = require('something');
}
else {
myExport = function() {
console.log('exported something else');
};
myRequired = require('something-else');
}
exports.myExport = myExport;
exports.someMore = myRequired;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)