5

The following code worked when run using Visual Studio Code live server. But threw an error when run as distinct file. I tested it online on my web site and in place of './course.js' and './student.js' with the full URL path and the error returned were:

Cross-Origin Request Blocked: The Same Origin Policy disallows readin the remote resource at .... (Reason: CORS header 'Access-Control-Allow-Origin' missing).

and

Loading module from “...” was blocked because of a disallowed MIME type (“application/octet-stream”)

In a different iteration in which I used che to set the request header to allow CORS I was still unable to run the code properly as the browser returned the following error:

  SyntaxError: export declarations may only appear at top level of a module

Please keep in mind that I am not using node.js, nor any form of server side rendering, but rather trying to import code without having to add for each JS file.

Example

File 1 (course.js)

export function Course() {
   this.name = '';
}

File 2 (student.js)

import { Course } from './course.js';

export function Student() {
   this.course = new Course();
}

File 3 (index.html)

<html ...
<body>
    <script type='module'>
        import { Student } from './student.js';

        var x = new Student();
        x.course.name = 'xxx';
        console.log(x.course.name)
   </script>
 ....
Conk
  • 73
  • 1
  • 5

1 Answers1

-1

https://gomakethings.com/an-intro-to-import-and-export-with-es-modules:

ES modules also won’t run if you try to just open an HTML file in the browser using the file:// origin. You need to run a local server for local development.

Bummer, right?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
sheriffderek
  • 8,848
  • 6
  • 43
  • 70