Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active December 19, 2015 21:39
Show Gist options
  • Save ryanflorence/6021229 to your computer and use it in GitHub Desktop.
Save ryanflorence/6021229 to your computer and use it in GitHub Desktop.

ES6 -> CJS Tranpilation for UMD

ES6 and AMD require paths are raw, you can make them mean whatever you want, but by default mean baseUrl+path. In npm the paths are relative to the file calling require if the path starts with a directory separater, if there is no separator it looks in node_modules. For example:

// looks in node_modules
// we'll call this a "vendor require"
var handlebars = require('handlebars');
// looks relative to this file
// we'll call this a "relative require"
var local = require('./handlebars');

There is no such convention in AMD or ES6. Given this ambiguity we will need to be more intelligent with the umd transpilation.

Here's an idea, look in package.json

Perhaps we can check the dependencies in package.json to distinguish between local and vendor requires.

Given this package.json:

{
  "dependencies": {
    "rsvp": "*"
  }
}

The following module code...

import { EventTarget } from 'rsvp/events'
import format from 'time/format'

becomes:

var EventTarget = require('rsvp/events').EventTarget;
var format = require('./time/format');

(amd/global umd code omitted for clarity.)

Nested Files

Because node modules require relative, the transpiler needs to be aware of the current file's path.

Given a file nested two directories from root with the same code:

import { EventTarget } from 'rsvp/events'
import format from 'time/format'

The output becomes:

var EventTarget = require('rsvp/events').EventTarget;
var format = require('../../time/format');

Limitations

Vendor requires for global modules will not work. All vendor requires must map to an entry in package.json's dependencies or devDependencies.

@addyosmani
Copy link

@geddski I haven't been able to locate any references to that either. Do you have a link/citation that we could read up on? I agree completely - that would be a terrible idea.

My interpretation of current module loader plans are inline with what @domenic described - the current semantics are very likely to be matched per import format from 'time/format' => var format = require("time/format") and opting for the relative path solution makes the most sense.

I need to catch-up with http://esdiscuss.org/topic/modulenaminganddeclarations#content-100.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment