【发布时间】:2021-05-07 14:42:33
【问题描述】:
我已经完全模块化了两个类 Person 和 Teacher ,如下所示。但是当我试图调用 Teacher 类并在 Index.html 中使用它的方法时,它会在 Chrome 浏览器的控制台窗口中生成一个错误:“Uncaught SyntaxError: Cannot use import statement outside a module”强>。我正在使用 Visual Studio Professional 2017 并使用 Chrome 浏览器打开 Index.html。我没有使用节点。即使使用 Firefox 打开 Index.html,它也会显示相同的错误,但描述略有不同:“SyntaxError: import declarations may only appear at top level of a module”。我的代码如下。
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}.`);
}
}
索引.js
import { Teacher } from "./Teacher";
const teacher = new Teacher('MyName', 'MyQualification');
teacher.printName();
teacher.printQualification();
最后是 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>
作为替代方案,我尝试使用以下行将 Index.js 明确定义为 Index.html 中的模块:
<script type="module" src="Index.js"></script>
但它会产生更大的错误,显示以下两条错误消息:
“CORS 策略已阻止从源“null”访问“file:///D:/Pendings/Object-oriented%20Programming_Mosh-Hamedani/Index.js”处的脚本:跨源请求是仅支持协议方案:http、data、chrome、chrome-extension、chrome-untrusted、https。"
“加载资源失败:net::ERR_FAILED”
为什么会这样?我偶然发现它是如此糟糕。仅仅因为这个单一的因素,我无法推进这个项目。那么我该如何解决呢?我是 JavaScript 新手,不知道方向。请帮忙。
【问题讨论】:
-
通过浏览器本身导入/导出javascript文件有点复杂。您可以在此处查看答案,并提供详细的分步说明:stackoverflow.com/a/62533794/10907180
-
您需要一台服务器。您不能从简单文件中执行此操作,因为文件没有有效的域名。像 React 这样的框架为你提供了一个运行在 3000 端口上的服务器用于开发。您可以使用类似的东西或在您的机器上安装服务器(例如 Apache 或 Nginx)
-
slebetman:感谢您的回复。我开始了解如何通过 Web 服务器运行文件,为此,我安装了 Node 并运行 live-server。但还有其他问题浮出水面。请参考下面的答案下面的cmets。我们的讨论向前推进了一点。您能否对下面提到的问题问题 1)、2) 和 3) 有所了解?
标签: javascript class visual-studio-2017 javascript-objects