html a标签module,class - Why can't I import a JavaScript module in an html file? - Stack Overflow

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

Object-oriented Programming

Object-oriented Programming

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值