named-register.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. (function () {
  2. /*
  3. * SystemJS named register extension
  4. * Supports System.register('name', [..deps..], function (_export, _context) { ... })
  5. *
  6. * Names are written to the registry as-is
  7. * System.register('x', ...) can be imported as System.import('x')
  8. */
  9. (function (global) {
  10. var System = global.System;
  11. setRegisterRegistry(System);
  12. var systemJSPrototype = System.constructor.prototype;
  13. var constructor = System.constructor;
  14. var SystemJS = function () {
  15. constructor.call(this);
  16. setRegisterRegistry(this);
  17. };
  18. SystemJS.prototype = systemJSPrototype;
  19. System.constructor = SystemJS;
  20. var firstNamedDefine, firstName;
  21. function setRegisterRegistry(systemInstance) {
  22. systemInstance.registerRegistry = Object.create(null);
  23. systemInstance.namedRegisterAliases = Object.create(null);
  24. }
  25. var register = systemJSPrototype.register;
  26. systemJSPrototype.register = function (name, deps, declare, metas) {
  27. if (typeof name !== 'string')
  28. return register.apply(this, arguments);
  29. var define = [deps, declare, metas];
  30. this.registerRegistry[name] = define;
  31. if (!firstNamedDefine) {
  32. firstNamedDefine = define;
  33. firstName = name;
  34. }
  35. Promise.resolve().then(function () {
  36. firstNamedDefine = null;
  37. firstName = null;
  38. });
  39. return register.apply(this, [deps, declare, metas]);
  40. };
  41. var resolve = systemJSPrototype.resolve;
  42. systemJSPrototype.resolve = function (id, parentURL) {
  43. try {
  44. // Prefer import map (or other existing) resolution over the registerRegistry
  45. return resolve.call(this, id, parentURL);
  46. } catch (err) {
  47. if (id in this.registerRegistry) {
  48. return this.namedRegisterAliases[id] || id;
  49. }
  50. throw err;
  51. }
  52. };
  53. var instantiate = systemJSPrototype.instantiate;
  54. systemJSPrototype.instantiate = function (url, firstParentUrl, meta) {
  55. var result = this.registerRegistry[url];
  56. if (result) {
  57. this.registerRegistry[url] = null;
  58. return result;
  59. } else {
  60. return instantiate.call(this, url, firstParentUrl, meta);
  61. }
  62. };
  63. var getRegister = systemJSPrototype.getRegister;
  64. systemJSPrototype.getRegister = function (url) {
  65. // Calling getRegister() because other extras need to know it was called so they can perform side effects
  66. var register = getRegister.call(this, url);
  67. if (firstName && url) {
  68. this.namedRegisterAliases[firstName] = url;
  69. }
  70. var result = firstNamedDefine || register;
  71. firstNamedDefine = null;
  72. firstName = null;
  73. return result;
  74. };
  75. })(typeof self !== 'undefined' ? self : global);
  76. })();