【问题标题】:Import a module for local development导入本地开发模块
【发布时间】:2020-12-06 09:01:28
【问题描述】:

我想在我的 javascript 文件中导入一个模块(在我的例子中是threejs),以便让 vscode 的自动完成功能正常工作。当我使用

import * as THREE from './lib/three'

在我的工作 js 文件的顶部,自动完成功能将起作用,

但导入实际上被 CORS 跨域策略阻止,说同源规则允许从外部源文件读取(因为请求不是 http ?!)。

有人知道解决方法吗?到目前为止,我只能在没有 import 语句的情况下使用模块,因此无法使用自动完成功能。

这是我的代码:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="margin: 0">
    <h3>Hello</h3>
    <script type="module" src="sketch.js"></script>
</body>
</html>

还有sketch.js

import * as THREE from './lib/three';

const scene = new THREE.Scene();

提前致谢,祝您有美好的一天。 方扎内

【问题讨论】:

    标签: javascript import module es6-modules


    【解决方案1】:

    尝试在你的脚本标签&lt;script src="sketch.js" type="module"&gt;&lt;/script&gt;中添加type="module"

    您可以在此处阅读 js 模块:https://appdividend.com/2019/01/23/javascript-import-statement-tutorial-with-example/

    【讨论】:

    • 感谢您的回答!现在,当我尝试通过资源管理器打开 html 文件时,出现 CORS 同源错误(说 cors-request 不是 http),当我尝试通过简单的本地 http-server 打开 html 时,我收到错误消息加载模块失败的原因是不受支持的 mime 类型 ("")。后一个错误是否特定于three.js?
    • 您需要查看哪个请求失败。多一点信息会很好。
    • 这不是一个实际的请求(网络选项卡为空),但它表示由于跨域,CORS-Policy 阻止了读取外部资源。
    猜你喜欢
    • 2023-04-05
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2017-07-16
    • 2018-04-18
    相关资源
    最近更新 更多