vazco / universe-modules

Use ES6 / ES2015 modules in Meteor with SystemJS
https://atmospherejs.com/universe/modules
MIT License
52 stars 7 forks source link

Import exports from existing Meteor packages #15

Closed ghost closed 9 years ago

ghost commented 9 years ago

To bring existing Meteor packages into the ES2015 module system I have written the appended code to map the package exports to SystemJS.

Lets say there is the Meteor package sanjo:foo that exports Foo via api.export('Foo'). The mapping code maps this export to the package reference {sanjo:foo}. Because the package has only one export, Foo will also become the default export.

In your app that uses the ES2015 module system you can now use the export Foo via import {Foo} from '{sanjo:foo}'. Or via default import syntax: import Foo from '{sanjo:foo}'.

If the package would have another export Bar, you could import it via import {Bar} from '{sanjo:foo}'.

An example app that uses this can be found here.

var registerPackage = function (packageName) {
  var normalizedPackageName = '{' + packageName + '}';
  System.register(normalizedPackageName, [], function (_export) {
    return {
      setters: [],
      execute: function () {
        var packageExports = Package[packageName];
        _.forEach(packageExports, function (packageExport, packageExportName) {
          _export(packageExportName, packageExport);
        });

        var packageExportNames = _.keys(packageExports);
        if (packageExportNames.length === 1) {
          _export('default', packageExports[packageExportNames[0]]);
        }
      }
    };
  });
};

_.chain(Package).keys().forEach(registerPackage).value();
MacRusher commented 9 years ago

Very nice idea! This would be a great opt-in option, as I'm afraid that making this the default could be little confusing.

For now, can I use your snippet in universe:modules docs?

ghost commented 9 years ago

For now, can I use your snippet in universe:modules docs?

Sure. The code is MIT licensed. ;-)

cristo-rabani commented 9 years ago

Hello @Sanjo

We decided to add access to exported variables by "!var" in future we want to protect against using not declared global variables in import.js(x) files for developing mode.

import {DDP} from '{ddp}!vars'
import {UniCollection, UniUsers} from '{vazco:universe-collection}!vars'

https://github.com/vazco/universe-modules#user-content-loading-package-level-variables