问题描述
test.html
<!DOCTYPE html>
<html>
<head>
<Meta charset="utf-8">
<title>Test</title>
</head>
<body>
<script type="module" src="main.js"></script>
</body>
</html>
auxiliary.js
export let greeting = 'hello';
main.js
import { greeting } from './auxiliary.js';
document.write(greeting);
在Web Console中有2条警告:
- 跨域请求被阻止:“同源策略”不允许在...读取远程资源(原因:CORS请求不是http)。
- 此文档中不允许使用模块源URI:...。
编辑: 正如areallytinydot和Abhinav Nigam所建议的,我在import语句中添加了curly。警告仍然存在,页面仍为空白。
解决方法
导入应该看起来像这样,因为它不是默认导出。
import { greetings } from 'auxiliary.js'
第document.write(greeting)
行可能是导致它的原因。在这种情况下,console.log(greeting)
应该可以工作。你可以尝试使用这个吗? source
document.open()
document.write(greeting)
document.close()
,
我在这里看到2个问题:
- 您没有导入assistant.js
- 您已将问候语导入为默认导入,而应导入为
CallableFunction
我需要设置一个本地Web服务器(实际上并不需要页面中的先决条件。): https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server
这导致此错误:
A call to document.write() from an asynchronously-loaded external script was ignored.
将其更改为console.log()后,问候语将显示在Web控制台中。