"Cannot use import statement outside a module" 导入自制时 class
"Cannot use import statement outside a module" when importing a self made class
我查看了其他几个问题并尝试了很多,但我找不到问题所在。
这些是我从 HTML 文件导入的:
<script src="./script/Graph.js" type="module"></script>
<script src="./script/Main.js"></script>
Graph.js:
export default class Graph {
constructor() {
this.vertices = [];
this.edges = [];
this.numberOfEdges = [];
}
...followed by several functions
}
Main.js:
import Graph from "./Graph.js";
感谢任何提示:)
要在您的文件中使用 import - export
,您需要将脚本文件的类型指定为 module
所以更正后的代码是
<script src="./script/Graph.js" type="module"></script>
<script src="./script/Main.js" type="module"></script>
阅读更多关于Modules
额外:
您在使用 import-export
时可能会遇到 CORS(跨源资源共享策略),要解决此问题,您可以使用以下方法之一
- Live server extension visual studio 代码
- Node express.js 提供静态文件
- Github pages 将您的项目发布到 github 存储库并使用 github 页面来提供您的文件
我查看了其他几个问题并尝试了很多,但我找不到问题所在。
这些是我从 HTML 文件导入的:
<script src="./script/Graph.js" type="module"></script>
<script src="./script/Main.js"></script>
Graph.js:
export default class Graph {
constructor() {
this.vertices = [];
this.edges = [];
this.numberOfEdges = [];
}
...followed by several functions
}
Main.js:
import Graph from "./Graph.js";
感谢任何提示:)
要在您的文件中使用 import - export
,您需要将脚本文件的类型指定为 module
所以更正后的代码是
<script src="./script/Graph.js" type="module"></script>
<script src="./script/Main.js" type="module"></script>
阅读更多关于Modules
额外:
您在使用 import-export
时可能会遇到 CORS(跨源资源共享策略),要解决此问题,您可以使用以下方法之一
- Live server extension visual studio 代码
- Node express.js 提供静态文件
- Github pages 将您的项目发布到 github 存储库并使用 github 页面来提供您的文件