1

I've modularised two classes Person and Teacher exactly as shown down below. But when I'm trying to call the Teacher class and use its methods in Index.html, it's generating an error in the console window of Chrome browser saying: "Uncaught SyntaxError: Cannot use import statement outside a module". I'm using Visual Studio Professional 2017 and opening Index.html with Chrome browser. I'm not using Node. Even if Index.html is opened with Firefox it displays the same error with a little different description: "SyntaxError: import declarations may only appear at top level of a module". My codes follow.

Person.js

export class Person {
    constructor(name) {
        this.name = name;
    }

    printName() {
        console.log(`My name is ${this.name}.`);
    }
}

Teacher.js

import { Person } from "./Person";

export class Teacher extends Person {
    constructor(name, degree) {
        super(name);
        this.degree = degree;
    }

    printQualification() {
        console.log(`My qualification is ${this.degree}.`);
    }
}

Index.js

import { Teacher } from "./Teacher";
const teacher = new Teacher('MyName', 'MyQualification');
teacher.printName();
teacher.printQualification();

And finally, Index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Object-oriented Programming</title>
</head>
<body>
    <h1>Object-oriented Programming</h1>
    <script src="Index.js"></script>
</body>
</html>

As an alternative, I tried to explicitly define Index.js as a module in Index.html with the following line:

<script type="module" src="Index.js"></script>

But it generates even a bigger error displaying the following two error messages:

"Access to script at 'file:///D:/Pendings/Object-oriented%20Programming_Mosh-Hamedani/Index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https."

"Failed to load resource: net::ERR_FAILED"

Why is this happening? I've stumbled upon it so badly. Just because of this single factor I can't move ahead with the project. So how do I solve it? I'm new in JavaScript and can't figure out the direction. Please help.

priyamtheone
  • 517
  • 7
  • 22
  • Importing/Exporting javascript files by the browser itself is a bit complicated. You can check out an answer here with a good step-by-step explanation: https://stackoverflow.com/a/62533794/10907180 – MikoYats Feb 03 '21 at 11:29
  • You need a server. You cannot do this from a simple file because files don't have valid domain names. Frameworks like React gives you a server running on port 3000 for development. You can either use something like that or install a server on your machine (eg. Apache or Nginx) – slebetman Feb 17 '21 at 04:54
  • slebetman: Thanks for your reply. I've come to know about running the files through a web server, and for that, I've installed Node and running live-server. But there are other issues that popped out. Please refer to the comments below the answer below. We've moved ahead a bit with the discussion. Can you please shed some light on the problem issues 1), 2) and 3) mentioned down under? – priyamtheone Feb 18 '21 at 13:47

1 Answers1

1

Since this question is somewhat already answered in another question link, I'll just summarize and change some things.

  1. Install Node.js link
  2. Run npm install -g live-server
  3. Change the ff. in your code:
  • Change the import line in Teacher.js to include the file type. import { Person } from "./Person.js";
  • Change the import line in Index.js to include the file type. import { Teacher } from "./Teacher.js";
  1. Run live-server --port=1234 --entry-file=Index.html (Ensure you're running it on the same folder as your files.

Things to take note of:

  • We changed the imports to include file type because so far without the help of some tools, ambiguity of what to import is not supported. (more details here)
  • We used an HTTP server to fix the CORS policy issue due to the browser's inability to import stuff locally because of permission stuff.
MikoYats
  • 116
  • 4
  • MikoYats: Thanks for sharing the link of your step-by-step explanation. It helped me getting a basic understanding. This is what I did: 1) In Teacher.js- import { Person } from "./Person.js"; 2) In Index.js- import { Teacher } from "./Teacher.js"; However, can't rename Index.js to Index.mjs as doing so is jeopardising the JavaScript file and treating it as a simple text file and the codes in it are not being treated as codes but simple text instead. 3) In Index.html- 4) In command prompt- live-server --port=1234 --entry-file=Index.html – priyamtheone Feb 14 '21 at 12:53
  • Now everything is running fine. However, I have a few questions. 1) While trying to open Index.html with "live-server Index.html" in command prompt, though the page is opening but an error is showing in the console saying: 'Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.' Why is this happening? Why can't I use the default port of 8080? – priyamtheone Feb 14 '21 at 13:31
  • 2) Why couldn't I rename Index.js to Index.mjs as per your suggestion? While doing so why couldn't Visual Studio recognise it as a JavaScript module file and messing up all the internal codes? 3) After starting a live-server session through command prompt, how can I terminate it without closing the command prompt window? It seems, once the live-server starts, there's no way you can input any command in the command prompt. So how do I go about it? Please clarify my questions. – priyamtheone Feb 14 '21 at 13:34
  • 1.) You're receiving this error because of not renaming Index.js to Index.mjs. ".mjs" is used if you want to import other javascript files. Not using this extension causes this error. – MikoYats Feb 15 '21 at 11:14
  • 2.) What Visual Studio are you using? If it's Visual Studio Code, I think it supports it out of the box. Or try installing an extension that supports that file. If it's THE Visual Studio, here's a link to an issue: https://developercommunity.visualstudio.com/content/problem/1277175/no-syntax-highlighting-for-jsx-and-mjs-files.html – MikoYats Feb 15 '21 at 11:20
  • 3.) live-server uses the command prompt that you type on as a "process", meaning that window is used by "live-server" until it's stopped (using Ctrl + C). You can open up another command prompt window or tab to continue working. – MikoYats Feb 15 '21 at 11:23
  • You can use the default port 8080 unless another program is already using it. 1234 is just used as an example. – MikoYats Feb 15 '21 at 11:24
  • Regarding your last answer, I'm sure port 8080 is not being used by another program as I ran live-server right after I installed it. So there's no question of another program using it. I cross-checked. Moreover, if I'm receiving the error pertaining to question 1) because of not renaming Index.js to Index.mjs, then how come everything is working fine when I'm running it with the command: live-server --port=1234 --entry-file=Index.html? As Index.js hasn't been renamed to Index.mjs in this case too, shouldn't it show the same error? But it's running absolutely error-free. Why's this difference? – priyamtheone Feb 16 '21 at 16:43
  • Regarding your answer 2), I'm using Visual Studio Professional 2017. I checked the link you provided on the issue of syntax not being highlighted in .mjs files. But I couldn't find any proper solution there. All they mentioned of are that they reported the problem to the engineering team/product group and that they'd be rolling out a solution for the highlighting issue soon. That's just it. Did I miss something? Also, .mjs files are treated as simple text files in VS Professional 2017 and not JavaScript files. Don't know why! Please enlighten me more about this issue if you can. – priyamtheone Feb 16 '21 at 16:52
  • 1.) My bad, got confused there a bit. Anyway, you could still use ".js" instead of ".mjs", you just need to indicate the `type="module"` in the – MikoYats Feb 17 '21 at 04:22
  • About `.mjs`, here's a better article about it, https://jakearchibald.com/2017/es-modules-in-browsers/ – MikoYats Feb 17 '21 at 04:26
  • That article on ECMAScript modules is quite valuable. Bookmarked it for future reference. On a side note, Visual Studio Developer Community advises to update VS 2017 to the latest version to get rid of the problem pertaining to ".mjs" files. Updated VS 2017 to the latest 15.9.33 version, but of no avail. ".mjs" files are still ignored. Seems like have to wait till they come up with some concrete solution. – priyamtheone Feb 18 '21 at 13:41