How to import and export members using Ecmascript modules in the browser?

Asked

Viewed 273 times

2

I am trying to import a class, but I am making one or several mistakes. Can anyone enlighten me about?

Filing cabinet js/calendar:

export default class Calendar {
  constructor(date) {
    console.log(date);
  }
}

Filing cabinet index.html (note that I am trying to import the class Calendar):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Calendar</title>
</head>

<body>
  <div id="calendar"></div>
  <script>
    import { Calendar } from './js/calendar';

    var calendar = new Calendar('2020-02-01');
  </script>
</body>

</html>

However, I am getting this error:

SyntaxError: import declarations may only appear at top level of a module
  • import { Calendar } from './js/calendar'

  • I already tried this, it returns me this error: "Syntaxerror: import declarations may only appear at top level of a module"

  • 2

    In HTML <script type="module">

1 answer

4

You need to run your code as a module.

A Javascript module is a file or simple script that contains JS code.

There is no Javascript keyword to define a module.

But in HTML5 there is an attribute in the tag <script> which indicates which type of script is represented. It is the attribute type, whose value:

  • When omitted or informed Mime Type JavaScript indicates that the code should be handled with a standard Javascript script.

  • When its value is module indicates that the code will be treated in strictly speaking and the keywords import and export will be available.

  • Any other value will be ignored by the browser.

In HTML5 just add the attribute type with the value module:

<script type="module">

Differences between modules and standard scripts

  • You need to pay attention to local tests - if you try to load the HTML file locally (for example, with a file://URL), errors will occur from CORS due to security requirements of the Javascript module. You need to do your tests through a server.

  • Note that you can get a different behavior from the script sections defined within the modules and not in the standard scripts. This is because modules use strict mode automatically.

  • No need to use attribute deferwhen loading a module script, modules are automatically delayed.

  • Module features are imported into the individual scope of each script, they are not available in the global scope. Therefore, you will only be able to access the imported features in the script to which they were imported.

  • You will receive syntax errors shown in DevTools, but some of the debugging techniques will be restricted.

Read more on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.