【问题标题】:javascript import, export: simple example failingjavascript 导入、导出:简单示例失败
【发布时间】:2026-02-12 06:25:01
【问题描述】:

test.html

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>
    <script type="module" src="main.js"></script>
  </body>
</html>

辅助.js

export let greeting = 'hello';

main.js

import { greeting } from './auxiliary.js';

document.write(greeting);

在 Web 控制台中有 2 个警告:

  1. 跨域请求被阻止:同源策略不允许读取位于 ... 的远程资源(原因:CORS 请求不是 http)。
  2. 此文档中不允许使用模块源 URI:...。

问候语未显示在页面上。

编辑: 根据 areallytinydot 和 Abhinav Nigam 的建议,我在 import 语句中添加了花括号。警告仍然存在,页面仍然是空白的。

【问题讨论】:

    标签: javascript html import module export


    【解决方案1】:

    我在这里看到 2 个问题:

    1. 您没有导入auxiliary.js
    2. 您将问候语导入为默认导入,而应导入为import { greeting } from './auxiliary.js'

    【讨论】:

    • 我应用了问题 #2 中的建议。您能否详细说明问题 #1?
    • 我猜你还需要为auxiliary.js添加一个脚本标签。
    【解决方案2】:

    我需要设置一个本地网络服务器(实际上不需要页面中的先决条件。): 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 Console中。

    【讨论】:

      【解决方案3】:

      导入应该如下所示,因为它不是默认导出。

      import { greetings } from 'auxiliary.js'
      

      document.write(greeting) 行可能是导致它的原因。如果是这种情况,console.log(greeting) 应该可以工作。你能试试用这个吗? source

      document.open()
      document.write(greeting)
      document.close()
      

      【讨论】:

      • 我添加了卷发。警告仍然存在,页面仍然是空白的。