I use the jspm
in my project.
But I need the server side nodejs file to execute some instruction.
For example, I need to use the lodash
and found the guide in the https://github.com/systemjs/systemjs
var System = require('jspm').Loader();
System.import('lodash').then(function (_) { console.log(_); });
However, I want to use the lodash globally. Just like
var _ = System.import('lodash');
var myArr = _.map([1, 2, 3], function(n) { return n * 3; });
It will show
TypeError: _.map is not a function at Object. (/Users/joyfeel/javascript/jspm-test/index.js:49:16) at Module._compile (module.js:435:26) at normalLoader (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:199:5) at Object.require.extensions.(anonymous function) [as .js] (/usr/local/lib/node_modules/babel/node_modules/babel-core/lib/api/register/node.js:216:7) at Module.load (module.js:356:32) at Function.Module._load (module.js:311:12) at Function.Module.runMain (module.js:467:10) at Object. (/usr/local/lib/node_modules/babel/lib/_babel-node.js:144:25) at Module._compile (module.js:435:26) at Object.Module._extensions..js (module.js:442:10)
Why does the lodash
only be used in .then
scope?
Could anyone tell me how to figure it out? Suppose we want to System.import
other modules and use it?
_
can only be accessed in the scope of then
because System.import
always returns a Promise.
Therefore you have to wait for the Promise to be resolved before you can access its result.
Anyway i would not recommend you to use lodash globally.
But when you really want to use _
globally you can do something like:
System.import('lodash').then(function(_) {
GLOBAL._ = _;
});
Still you have to make sure that all code that uses GLOBAL._ waits till the Promise from the lodash import is resolved. But again: i would discourage you doing it that way but recommend that you import lodash in every module that needs it.