Created
August 23, 2016 12:29
-
-
Save rjgotten/7e1ecc8aa6e909add99f772e70d238cb to your computer and use it in GitHub Desktop.
More complete AMD loader support for can-util/js/import/import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var isFunction = require('../is-function/is-function'); | |
var global = require("../global/global")(); | |
/** | |
* @module {function} can-util/js/import/import import | |
* @parent can-util/js | |
* @signature `importModule(moduleName, parentName)` | |
* | |
* ```js | |
* var importModule = require("can-util/js/import/import"); | |
* | |
* importModule("foo.stache").then(function(){ | |
* // module was imported | |
* }); | |
* ``` | |
* | |
* @param {String} moduleName The module to be imported. | |
* @param {String} [parentName] A parent module that will be used as a reference for resolving relative module imports. | |
* @return {Promise} A Promise that will resolve when the module has been imported. | |
*/ | |
module.exports = function(moduleName, parentName) { | |
return new Promise(function(resolve, reject) { | |
try { | |
if(typeof global.System === "object" && isFunction(global.System["import"])) { | |
global.System["import"](moduleName, { | |
name: parentName | |
}).then(resolve, reject); | |
} else if(global.define && global.define.amd){ | |
// Inline-define a loader plugin that will be used to obtain local | |
// `require` functions. These will offer the expected support for | |
// relative module id lookups and will respect module-local mappings | |
// set up via `require.config({ map : ... })`. | |
if ( !global.require.defined( "can-require-local" )) { | |
global.define("can-require-local", [], function() { | |
return { | |
load: function(name, require, load, config) { | |
name+="?can-require-local"; | |
global.define(name, ["require"], function(require) { | |
return require; | |
}); | |
global.require([name], function(require) { | |
global.require.undef(name); | |
load(require); | |
}, function(err) { load.error(err); }); | |
} | |
} | |
}); | |
} | |
// If a parent module name is present, always go through a local require | |
// function. | |
if (parentName) { | |
global.require(["can-require-local!"+parentName], function(local){ | |
local([moduleName], resolve, reject); | |
}, reject); | |
} else { | |
global.require([moduleName], resolve, reject); | |
} | |
} else if(global.require){ | |
resolve(global.require(moduleName)); | |
} else { | |
// ideally this will use can.getObject | |
resolve(); | |
} | |
} catch(err) { | |
reject(err); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment