Angular 2 + Zone.js +常见的js模块:IF语句exception,即使在假的情况下也执行代码

我试了一下检查。 这绝对是一个exception。 我有一个Angular 2服务,加载@type定义( @type 2),然后加载commmon.js模块( visionmedia / debug )。 在common.js模块中,我有一个简单的if语句,即使条件为false并且不应该执行代码,也会触发错误。 Angular应用程序使用system.js来加载模块。

常规代码 if (false) { console.log('This code is not executed') }正常行为,没有任何反应

exception代码: if (false) { exports.humanize = require('ms'); } if (false) { exports.humanize = require('ms'); }它会触发Error: zone.js:101 GET http://localhost:8002/ms.js 404 (Not Found)

错误本身是有效的。 事实上,这个脚本是不会被发现的。 严重的错误是不应该出现在第一位。 它应该被虚假的条件阻止。 在我看来, zone.js以某种方式parsing指令,即使这种情况是错误的。 我能做些什么来避免这种情况? 我需要检查是否需要一个或另一个path取决于如果相同的脚本在服务器或前端调用。

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使用正则expression式来检测导入语句。 也许它使用相同的方法来检测出口报表。

这不是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; 

问题解决了。 看起来zone.js与这个问题无关。 我从system.js社区获得了帮助。 检查这个答案 。

@guybedford

这是SystemJS中的依赖分析通过CommonJS的静态parsing所需要的方式 – 这是使CommonJS支持asynchronous加载的唯一方法。 尝试添加:

 System.config({ map: { ms: '@empty' } });