0

I am trying to import a module to my index.html file.

Here is the code:

// Index.html:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title></title>

</head>

<body>

<div></div>

  <script type="module" src="module.js"></script>
  <script type="text/javascript">

    import { addTextToBody } from 'module.js';

    addTextToBody('some text here');

  </script>
</body>
</html>

And the js:

export function addTextToBody(text) {

  const div = document.createElement('div');
  div.textContent = text;
  document.body.appendChild(div);

}

I am getting these errors:

Uncaught SyntaxError: Unexpected token { - Line 18

Access to Script at 'module.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.

How can I fix this?

2 Answers2

1
  1. module.js should be ./module.js
  2. You don't need to import the module at the beginning of the page (but you can).
  3. Using import requires the script to be of type module not just the imported script.
  4. You should place modules imports in <head> (at the very beginning).

The following example works (I cut out unessential parts):

<!-- index.html -->
<meta charset="utf-8">

<script type="module">
  import { addTextToBody } from './module.js';

  addTextToBody('some text here');
</script>
// module.js
export function addTextToBody(text) {
  const div = document.createElement('div');
  div.textContent = text;
  document.body.appendChild(div);
}

The code provided above will work with Firefox, but not with Chrome. It appears you are using Chrome (I assume that from your error message). Chrome strictly forbids access to resources with the file:// protocol. There are a handful solutions:

  1. Host your code with a webserver (e.g. nginx).
  2. Use a different webbrowser (e.g. Firefox).
  3. Disable web security altogether, refer to this answer.
asynts
  • 1,519
  • 2
  • 16
  • 27
0

Try:

import { addTextToBody } from './module.js';
Killer Death
  • 411
  • 2
  • 10