Module loader interop scenarios

Luke Hoban lukeh at microsoft.com
Fri Nov 11 11:13:40 PST 2011


There have been a few threads recently which have touched on interop scenarios for using ES6 modules and module loaders in concert with existing ES5 code.  I'm not yet clear though exactly which of these scenarios the existing proposal addresses.

At a high level - there are four interop scenarios that we want to support - (1) modules defined in ES6 syntax and consumed in ES6 syntax, (2) modules defined in ES6 syntax and consumed in ES5 syntax, (3) modules defined in ES5 syntax and consumed in ES6 syntax, and (4) modules defined in ES5 syntax and consumed in ES5 syntax.

(1) is well covered in the examples on the modules_examples page [1].

(2) we've discussed in some detail on the list previously.  The suggestion I've seen, and which I like, is that Object.System will be available to ES5 syntax, and be the system provided module loader.  With that, the below variant on the example from modules_examples should work:

        <script type="harmony">
        module math {
            export function sum(x, y) {
                return x + y;
            }
            export var pi = 3.141593;
        }
        </script>
        <script type="text/javascript">
        Object.System.load("math", function(math) {
            var sum = math.sum;
            var pi = math.pi;
            alert("2π = " + sum(pi, pi));
        }
        </script>

(3) I can't quite piece together whether the current proposal supports this - but if it does, it is somewhat indirect.  This would seem to be an important interop scenario, to allow libraries to continue offering a single codebase defined in ES5 syntax that can be consumed using a polyfill from either ES6 or ES5 syntax.  Does the below example behave as I'm expecting?  Any reason why the module loaders API doesn't include a 'defineModule' function that provides the equivalent of AMD 'define', so that existing AMD code (or any other interoperable JavaScript module pattern) can be consumed as ES6 modules from ES6 syntax?

        <script type="text/javascript">
        function sum(x, y) {
            return x + y;
        }
        var pi = 3.141593;
        Object.System.loaded.math = Object.System.createModule({
            sum: sum,
            pi: pi
        }, {});
        </script> 
        <script type="harmony">
        import {sum, pi} from math;
         
        alert("2π = " + sum(pi, pi));
        </script>

(4) would be a natural consequence of (2) + (3), and would ensure that module loaders is useful as an API-only abstraction separately from its connection to the specific ES6 syntax.

Luke

[1] http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples


More information about the es-discuss mailing list