I am trying to import a module in JavaScript. In python
, it's simple, you just import what you want with import
.
Apparently javascript
it also seems simple. In my case, I am trying to implement the example that appears in Using JavaScript code modules
However, I am getting this error in google chrome Uncaught ReferenceError: Components is not defined
. What will I be doing wrong?
my_module.jsm
var EXPORTED_SYMBOLS = ["foo", "bar"];
function foo() {
return "foo";
}
var bar = {
name : "bar",
size : 3
};
var dummy = "dummy";
test.js
Components.utils.import("resource://my_module.jsm");
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
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>hola</h1>
<script src="test.js"></script>
</body>
</html>
Forget about
Components
, it's not standard, but I propose you an alternative where it IS possible to import another JavaScript file using standard means, this trick I learned on original SO:Almost as easy as an import in
pyton
, only it's asynchronous :PBy the way, you also have a
jQuery.getScript()
, or even usingAjax
to load JavaScript code.There are ways that work in all browsers.
By the way, Components will not work in Chrome or other browsers, it is not part of the current standard (Living standard).
That's made for
jsm
, which is modular javascript, a Gecko proprietary piece for extending Firefox.Components
it is not standard and its use in web development is not recommended according to the Mozilla Developer Network (MDN) site.Translation of the page about the object
Components
on MDN :Components
is not standard, however you could make use ofES6
andBabel + Webpack
to perform theimports
.