According to How do I include a JavaScript file in another JavaScript file?, browsers have had support for loading ECMAScript modules directly.
So why does this not work on my local computer
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<script type="module">
import { hello } from './hello.js'; // Or the extension could be just `.js`
hello('world');
</script>
</body>
</html>
hello.js
export function hello(text) {
alert(text);
}
The console keeps giving me CORS error
Access to script at 'file:///C:/Users/Dave/Desktop/JavascriptImportExport/hello.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, chrome-untrusted, https.
CodePudding user response:
You cannot load modules from file://
protocol URLs.
You need a web server for this. If you're working with VS Code and just need a webserver to test and learn, I recommend you install the Live Server extension.
The error message already tells you this:
Cross origin requests are only supported for protocol schemes:
http, data, chrome, chrome-extension, brave, chrome-untrusted, https.