Import existing library with JavaScript ES6 Modules

d13 picture d13 · Mar 9, 2014 · Viewed 9.7k times · Source

How can an existing library be loaded and run using JavaScript's ES6 Modules?

For example, suppose I need to load an existing polyfill:

import {poly} from "thirdParty/poly"; 

How can I run the imported poly script and load its properties into the current namespace without changing the source?

Here are two practical problems to help clarify the problem I'm trying to solve:

  1. I have a script called rafPolyfill.js which is a polyfill for window.requestAnimationFrame. I need to import it into the global scope and run it immediately as soon as it loads. This is easy to do with a <script> tag:

It runs and loads itself into the global scope. How is can this be done using ES6 modules?

  1. I have another script called Font.js which is a pre-loader for fonts. It let's you create new font object like this:

    var font = new Font();

I used Font.js by loading it with a script tag, like this:

<script src="Font.js"><script>

Without accessing, changing, or understanding the source code of this script, how is it possible to use ES6 modules to load and use the in the same way that I would with a <script> tag? I just need these scripts to run when they're loaded and take care of themselves.

A possible solution might be using the module Loader API:

http://wiki.ecmascript.org/doku.php?id=harmony:module_loaders

This document describes global binding of the System loader, but I'm afraid I don't have the vocabulary to fully understand what it's trying to explain. Any help in decoding this document would be greatly appreciated!

Answer

d13 picture d13 · Mar 16, 2014

This answer is: "No, based on the ES6 spec it's not possible to load and run a global script the same way you can with a script tag."

But there is a solution: SystemJS

https://github.com/systemjs/systemjs

It's a universal module loader for ES6 modules, AMD modules, and global scripts (anything you load with the <script> tag)