Import modules in JavaScript


I'm trying to import a module into JavaScript. In python , because it's simple, you just import what you want with import .

In javascript apparently also seems simple. In my case, I'm trying to implement the example that comes out in Using JavaScript code modules

However, I get this error in google chrome Uncaught ReferenceError: Components is not defined . What will I be doing wrong?


var EXPORTED_SYMBOLS = ["foo", "bar"];

function foo() {
  return "foo";

var bar = {
  name : "bar",
  size : 3

var dummy = "dummy";



alert(foo());         // displays "foo"
alert(bar.size + 3);  // displays "6"
alert(dummy);         // displays "dummy is not defined" because 'dummy' was not exported from the module


<!DOCTYPE html>
    <meta charset="utf-8">
    <script src="test.js"></script>
asked by Javier Cárdenas 05.02.2016 в 03:07

3 answers


Components is not standard and its use in web development is not recommended according to the Mozilla Developer Network (MDN) site.

Translation of the page on the object Components in MDN :




This feature is not standard and is not in plans to be standard. Do not use in web pages in production: it will not work for all users. There may also be many incompatibilities and their behavior may change in the future.




This object is not designed to run with chrome privileges. Expose this object to the web was an error. If you use this object on your website, your page can be broken at any time! In the current versions of Firefox only a few interfaces required for its operation are active. Do not use Components !

answered by 05.02.2016 / 04:34

Forget about Components , it is not standard, but I propose an alternative where YES it is possible to import another JavaScript file using standard media, this truco that I learned in original SO:

// declaras un función que agregue el script a la cabecera del HTML
// y te notifique cuando el archivo termino de cargarse
function import(url, callback)
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    // compatibilidad cross browser 
    script.onreadystatechange = callback;
    script.onload = callback;

// ... así se usa

import("url/del/archivo.js", function() {
  // aqui ya se cargo el script, de forma global, como cualquier otro.

Almost as easy as an import in pyton , only it is asynchronous: P

By the way, you also have jQuery.getScript() , or even using Ajax to load JavaScript code.

There are ways that work in all browsers.

By the way, Components will not work in Chrome or other browsers, is not part of the current standard (Living standard).

This is done for jsm , which is modular javascript, a Gecko piece for extend Firefox.

answered by 05.02.2016 в 04:30

Components is not standard, however you could use ES6 and Babel + Webpack to make the imports .

answered by 05.02.2016 в 21:04