Reputation:
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?
Upvotes: 1
Views: 10546
Reputation: 2423
module.js
should be ./module.js
import
requires the script to be of type module
not just the imported script.<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:
Upvotes: 6