---
title: "在浏览器和 Node.js 中修复 Cannot use import statement outside a module"
description: "SyntaxError: Cannot use import statement outside a module 表示文件以经典脚本或 CommonJS 的方式运行了。把它作为模块加载，同一条 import 就能运行。"
canonical: "https://logbrew.co/zh-Hans/errors/cannot-use-import-statement-outside-a-module"
last_updated: "2026-11-21"
---

# 在浏览器和 Node.js 中修复 Cannot use import statement outside a module

`SyntaxError: Cannot use import statement outside a module` 表示文件以经典脚本或 CommonJS 的方式运行了。把它作为模块加载，同一条 `import` 就能运行。

2026年11月21日 用 Chrome 157、Safari 27.2、Node.js 22.18.0和@logbrew/browser 0.1.22 实测

作者 [Furkan Erday](https://github.com/furkanerday). Furkan Erday 是 LogBrew 的创始人，每天用 Claude Code 和 Codex 开发 LogBrew。

Canonical: https://logbrew.co/zh-Hans/errors/cannot-use-import-statement-outside-a-module

## 5 个 script 标签如何处理 1 条 `import`

| 页面的加载方式 | 代码已运行 | LogBrew 中的问题 |
| --- | --- | --- |
| 没有 type 的 `<script src>` | 否 | `SyntaxError` |
| 内联 `<script>` | 否 | `SyntaxError` |
| 来自其他源的 `<script src>` | 否 | `Error`，行号 0 |
| `type="module"` 脚本中的 SDK | 否 | 否 |
| `<script type="module">` | 是 | 没有错误 |

Chrome 157 和 Safari 27.2 对每个标签的结果都相同。

## 找出文件在哪里以经典脚本运行

### 检查加载文件的 script 标签

标签没有 `type` 属性，所以浏览器把 `app.js` 当作经典脚本读取，而经典脚本不能使用 `import`。Chrome 157 停在第 1 行第 1 列，文件中任何一行都还没运行。内联脚本给出同样的消息。

```bash
<!-- index.html -->
<script src="/app.js"></script>

// app.js
import { pour } from "./tap.js";

pour("IPA");
```

输出

```text
Uncaught SyntaxError: Cannot use import statement outside a module
```

### 同一个文件在 Safari 中的消息不同

Safari 27.2 读取同一个 `app.js`，抛出 `SyntaxError: Unexpected token '{'. import call expects one or two arguments.`。这条消息说的是 `import()` 调用，没有提到模块。原因和修复方法都一样。

输出

```text
SyntaxError: Unexpected token '{'. import call expects one or two arguments.
```

### 经典脚本里的 export 同样会失败

只做导出的文件用经典标签加载时，会停在第一个 `export`。Chrome 报 `Unexpected token 'export'`，Safari 报 `Unexpected keyword 'export'`。两者都说明页面把一个模块当作经典脚本加载了。

```bash
// tap.js, loaded with <script src="/tap.js"></script>
export function pour(beer) {
  document.body.dataset.poured = beer;
}
```

输出

```text
Uncaught SyntaxError: Unexpected token 'export'
```

### 在 Node.js 中查看 package.json 的 type 字段

当 `package.json` 里写着 `"type": "commonjs"` 时，Node.js 22.18.0 抛出同样的消息。堆栈经过 CommonJS 加载器中的 `wrapSafe`。没有 `type` 字段时，Node.js 把文件作为模块运行，并输出一条警告而不是错误。

```bash
// package.json
{ "name": "lab", "type": "commonjs" }

// node app.js
import { pour } from "./tap.js";
```

输出

```text
import { pour } from "./tap.js";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (node:internal/modules/cjs/loader:1620:18)
    at Module._compile (node:internal/modules/cjs/loader:1662:20)
```

## 把文件作为模块加载

### 给 script 标签加上模块类型

在同一个标签上加 `type="module"` 后，`app.js` 和其中的 `import` 在 Chrome 157 和 Safari 27.2 中都运行了。浏览器会自己加载 `tap.js`。如果还有经典标签在加载 `tap.js`，请删掉它，因为它仍会停在 `export`。

```bash
<script type="module" src="/app.js"></script>
```

### 在 package.json 中设置模块类型

在 `package.json` 中写上 `"type": "module"`，或把文件改名为 `.mjs`。两种做法都让我们的文件运行且没有警告。不管 `type` 字段怎么写，Node.js 都把 `.mjs` 文件当作模块，把 `.cjs` 文件当作 CommonJS。

```bash
// package.json
{ "name": "lab", "type": "module" }

// node app.js
```

输出

```text
poured IPA
```

### 先用经典脚本加载 LogBrew SDK

解析错误发生在该文件任何一行运行之前，所以错误监听器必须已经在页面上。浏览器要读完页面才运行模块脚本，所以模块脚本来不及。把 SDK 放在 `<head>` 中的经典脚本里，LogBrew 记录到了错误。把 SDK 放在 `type="module"` 脚本里，什么都没记录。

```bash
// logbrew.ts
import { installLogBrewBrowser } from "@logbrew/browser";

installLogBrewBrowser({ clientKey: "LOGBREW_BROWSER_KEY" });

// bun build logbrew.ts --format=iife --outfile=public/logbrew.js
// index.html, in <head> before every other script:
// <script src="/logbrew.js"></script>
```

## 我们实测看到的结果

我们在 `http://127.0.0.1:28180` 提供 1 个页面，先加载 `@logbrew/browser` 0.1.22，再用 Chrome 157 和 Safari 27.2 打开。我们用 5 种方式加载同一段代码，并从 `error` 事件中读取 `error.message`。

Chrome 说出了原因，Safari 没有。两个浏览器在使用 `type="module"` 时都运行了文件。来自其他源的脚本只给出 `Script error.`，没有文件名，行号为 0，因为浏览器会隐藏其他源脚本的细节。

Node.js 22.18.0 只在 `"type": "commonjs"` 时报错。没有 `type` 字段时，它运行了文件并输出下面的警告。

输出

```text
poured IPA
(node:37250) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///…/app.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to /…/package.json.
```

|  | Chrome 157 | Safari 27.2 |
| --- | --- | --- |
| 没有 type 的 `<script src>` | `Cannot use import statement outside a module` | `Unexpected token '{'. import call expects one or two arguments.` |
| 没有 type 的内联 `<script>` | `Cannot use import statement outside a module` | `Unexpected token '{'. import call expects one or two arguments.` |
| `tap.js`（含 `export`），经典标签 | `Unexpected token 'export'` | `Unexpected keyword 'export'` |
| 来自其他源的 `<script src>` | `Script error.` | `Script error.` |
| `<script type="module">` | 已运行 | 已运行 |

## 为什么经典脚本不能使用 import

MDN 关于这个错误的页面说，`import` 声明只能出现在模块的顶层，常见原因是文件没有作为模块运行。只有标签带 `type="module"` 时，浏览器才把文件当作模块读取。没有 type 时，浏览器把它当作经典脚本解析，并停在第一个 `import`。

经典脚本可以使用函数调用 `import()`。Safari 的消息说的是这个调用，所以它报告的是缺少参数，而不是缺少模块。

Node.js 对每个文件分别判断。它先看扩展名，再看最近的 `package.json` 中的 `type` 字段。按 Node.js 文档的说法，从 v22.7.0 和 v20.19.0 起，没有 `type` 字段且无法按 CommonJS 解析的文件会作为模块运行。

nodejs/node#39353 在 2021 年提出，让 Node.js 按入口文件而不是按 `package.json` 来判断。它在 2022 年被关闭。设置 `type` 或使用 `.mjs` 仍能让判断更明确，也能去掉警告。

1. `.mjs` `.cjs`
2. `package.json` `type`
3. 没有 `type` 字段时的语法检测

- [nodejs/node#39353](https://github.com/nodejs/node/issues/39353) Detect require vs. import based on the entry point, not package.json. 已关闭, 45 条评论.

## LogBrew 记录了什么

SDK 把每个解析错误记录为 1 个名为 `Browser error: SyntaxError` 的问题，聚合键为 `browser.error:SyntaxError`。问题中有文件路径和行号，没有堆栈帧，消息为 `redacted`，因为 SDK 不发送错误消息。

两个浏览器中的 import 和 export 错误都归入同一个问题，因为聚合键只包含错误类型。要改哪个文件，看 `sourcePath`。来自其他源的脚本成了另一个问题 `Browser error: Error`，行号为 0，没有文件路径。

SDK 放在模块脚本里时，LogBrew 对同一个页面什么都没记录。请像最后一步那样，在你的代码之前用经典脚本加载 SDK。

- `Browser error: SyntaxError`
  - `mechanism`: `browser.error`
  - `handled`: `false`
  - `sourcePath`: `/app.js`
  - `lineNumber`: `1`
  - 堆栈帧: 0
  - 聚合键: `browser.error:SyntaxError`
  - 消息: `redacted`
- `Browser error: Error`
  - `lineNumber`: `0`
  - 聚合键: `browser.error:Error`

## 常见问题

### Cannot use import statement outside a module 是什么意思？

文件里有 `import` 声明，但它在浏览器中以经典脚本运行，或在 Node.js 中以 CommonJS 运行。把它作为模块加载即可修复。

### 在浏览器中怎么修复？

给加载该文件的 script 标签加上 `type="module"`。在我们的测试中，同一个 `app.js` 随后在 Chrome 157 和 Safari 27.2 中都运行了。

### 在 Node.js 中怎么修复？

在 `package.json` 中写上 `"type": "module"`，或把文件改名为 `.mjs`。从 v22.7.0 起，Node.js 也会在没有 `type` 字段的包中检测模块语法，并输出一条警告。

### 为什么 Safari 显示的错误不一样？

对同一个文件，Safari 27.2 报的是 `Unexpected token '{'. import call expects one or two arguments.`。问题相同，修复方法也相同。

### 为什么 export 在经典脚本中也会失败？

经典脚本同样不能使用 `export`。Chrome 报 `Unexpected token 'export'`，Safari 报 `Unexpected keyword 'export'`。把那个文件也作为模块加载。

## 看到每个解析失败的脚本

LogBrew 浏览器 SDK 记录每个解析错误及其文件和行号，并按错误类型聚合。免费额度充足，无需绑卡。

[免费开始](https://logbrew.co/zh-Hans)

## 参考来源

- [MDN, SyntaxError: import declarations may only appear at top level of a module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/import_decl_module_top_level)
- [MDN, Using modules on the web](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules/Modules_on_the_web)
- [Node.js docs, Determining module system](https://nodejs.org/api/packages.html#determining-module-system)
- [nodejs/node#39353](https://github.com/nodejs/node/issues/39353)

## 更多错误修复

- [修复隐藏了消息、文件和行号的脚本错误](https://logbrew.co/zh-Hans/errors/script-error)
- [修复 Failed to fetch 错误，分清它的 3 种原因](https://logbrew.co/zh-Hans/errors/failed-to-fetch)
- [从消息入手修复 Kotlin 和 Android 中的 java.lang.NullPointerException](https://logbrew.co/zh-Hans/errors/nullpointerexception)
- [从完整消息和你自己的代码行入手修复 Minified React error #418 和 #185](https://logbrew.co/zh-Hans/errors/minified-react-error)
- [修复 AxiosError Network Error，找出你遇到的是 3 种原因中的哪一种](https://logbrew.co/zh-Hans/errors/axios-network-error)
- [修复 HTTP 499 错误，找出是谁先停止了等待](https://logbrew.co/zh-Hans/errors/http-499)
- [我们复现过的错误，以及每个错误的修复方法](https://logbrew.co/zh-Hans/errors)
