3

Wandering down a bit on MDN and on WHATWG, I saw that type="module" allows loading javascript modules on a webpage. But how do you execute the code defined in the module?

I have this module:

console.log('Starting module 1');

function addLiElement(text) {
    var li = document.createElement('li');
    li.classList.add('js-module-2');
    li.appendChild(document.createTextNode(text));

    document.querySelector('.output').appendChild(li);
}

console.log('End of module 1');

export default addLiElement;

The script is loaded in the webpage using <script type="module" src="module.js"></script> in <head>.

Now, if I call this classic javascript (in a <script src="mysqcript.js"></script>):

window.addEventListener('load', function () {
    addLiElement('Hello, I am a basic code.js');
});

Then Firefox says that the addLiElement function does not exist. If I use import {addLiElement} from "module-1.js";, then Firefox says that import can only be used inside modules. And the module's console.log do not appear inside the console.

So, Can we link normal javascript to modules? If so, how?

Xenos
  • 3,351
  • 2
  • 27
  • 50
  • See https://github.com/ModuleLoader/browser-es-module-loader for a way to do it – solarc Dec 22 '16 at 19:06
  • @Teemu FIrefox does support import/export (hence the `import cannot be used outside module`), but I didn't get how to use them to call the module's code from page's code – Xenos Dec 23 '16 at 13:27
  • Reading the accepted answer in the linked dup says, that the __syntax__ is supported, but the modules are not loaded ("_What isn't supported is module loading..._") – Teemu Dec 23 '16 at 13:31
  • 1
    @Teemu Okay, I understood "loading" as "being imported in the JS code" while it apparently means "not parsed at all" (because console.log and such inside module do nothing). Thanks ! – Xenos Dec 27 '16 at 16:03
  • They also say, that imported scripts are really working in MS Edge, have you tested? – Teemu Dec 27 '16 at 16:05
  • @Teemu No, because I have no Edge for now anywhere :\ (it's more for the curiosity than for targeting production) – Xenos Dec 27 '16 at 16:06

0 Answers0