如何正确使用System.import()?

我在我的项目中使用jspm

但是我需要服务器端的nodejs文件来执行一些指令。

例如,我需要使用lodash并在https://github.com/systemjs/systemjs中find指南

 var System = require('jspm').Loader(); System.import('lodash').then(function (_) { console.log(_); }); 

不过,我想在全球范围内使用lodash。 就像

 var _ = System.import('lodash'); var myArr = _.map([1, 2, 3], function(n) { return n * 3; }); 

它会显示

TypeError:_.map不是Object的函数。 (/ usr / local / lib / node_modules / babel / node_modules / babel)在Module._compile(module.js:435:26)处调用(/Users/joyfeel/javascript/jspm-test/index.js:49:16) (匿名函数)[as .js](/ usr / local / lib / node_modules / babel / node_modules / babel-core)/core/lib/api/register/node.js:199:5)在Object.require.extensions。在Module.load(module.js:356:32)在Function.Module._load(module.js:311:12)在Function.Module.runMain(module.js:216:7)/(/lib/api/register/node.js:216:7) module.js:467:10)在Object。 (/usr/local/lib/node_modules/babel/lib/_babel-node.js:144:25)在Module._compile(module.js:435:26)在Object.Module._extensions..js(module.js :442:10)

为什么lodash只能在范围内使用?

谁能告诉我如何解决? 假设我们想要System.import其他模块并使用它?

_只能在那个范围内访问,因为System.import总是返回一个Promise 。 因此,您必须等待Promise解决,然后才能访问其结果。 无论如何,我不会build议你在全球使用lodash。

但是,当你真的想在全球使用_你可以做一些事情:

 System.import('lodash').then(function(_) { GLOBAL._ = _; }); 

还是要确保所有使用GLOBAL._的代码都等待,直到lodash导入中的Promise被parsing。 但是,我会阻止你这样做,但build议你在需要它的每个模块中导入lodash。