javascript导入,导出:简单示例失败

问题描述

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条警告:

  1. 跨域请求被阻止:“同源策略”不允许在...读取远程资源(原因:CORS请求不是http)。
  2. 此文档中不允许使用模块源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个问题:

  1. 您没有导入assistant.js
  2. 您已将问候语导入为默认导入,而应导入为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控制台中。