0

I have an ES6 module (mymodule) and HTML page that has JS code that must be executed when a user opens the page. This is my module:

//mymodule.js
class TestClass {

    getString() {
        return "TestString";
    }
}
export {TestClass}

And this is my page:

//page.html
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Page</title>
        <script src="./mymodule.js" type="module"></script>
    </head>
    <body>
        <h1>Hello World!</h1>
        <script type="module">
            import {TestClass} from "./mymodule";
            let test = new TestClass();                 
            console.log("OUTPUT: " + test.getString());
        </script>
    </body>
</html>

Page.html and mymodule.js are in the same folder, however, when I open page.html in browser I have nothing on console (no error, no output) - I use FF 62.0.3. How to fix it?

Pavel_K
  • 10,748
  • 13
  • 73
  • 186

2 Answers2

3
   <script src="./mymodule.js" type="module"></script>

The above is not needed. You can remove it.

import {TestClass} from "./mymodule";

Browsers don't do file extension resolution the way Node.js does. (They can't, because they deal in URLs and not file systems, so there is no way to get a list of files in a directory).

You need to be explicit with the URL:

import {TestClass} from "./mymodule.js";

NB: You also need to load page.html over HTTP and not from the local file system.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Only one question - where did you take it from? http://exploringjs.com/es6/ch_modules.html#sec_modules-in-browsers , section 16.6.1.2, `import $ from 'lib/jquery';`. Note, it is module name without file extension. – Pavel_K Oct 23 '18 at 12:42
  • My memory (combined with testing your code and edits to it) – Quentin Oct 23 '18 at 12:44
  • Are you sure about `You also need to load page.html over HTTP and not from the local file system.`? I load page from local FS (double click on file) and Firefox loads ES6 module without problems. – Pavel_K Mar 13 '19 at 09:01
0

You can export your class to default keyword.

class TestClass {
    getString() {
        return "TestString";
    }
}
export default {TestClass}
André Teixeira
  • 2,392
  • 4
  • 28
  • 41
Asif vora
  • 3,163
  • 3
  • 15
  • 31
  • I showed just an example in reality I have much more classes ( > 100). Besides I want to have control over importing. – Pavel_K Oct 23 '18 at 12:26