0

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.

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • 1
    Opening local files directly (through `file://` URIs) has many restrictions in place, so that malicious programs can't access your data. To make it work, you have to access your site through a local server (google "localhost server" for more on how to set up one). – FZs Jul 29 '22 at 18:59

1 Answers1

1

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.
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
connexo
  • 53,704
  • 14
  • 91
  • 128