---
title: "Cannot use import statement outside a module을 브라우저와 Node.js에서 해결하기"
description: "SyntaxError: Cannot use import statement outside a module은 파일이 클래식 스크립트나 CommonJS로 실행됐다는 뜻이에요. 모듈로 불러오면 같은 import가 실행돼요."
canonical: "https://logbrew.co/ko/errors/cannot-use-import-statement-outside-a-module"
last_updated: "2026-11-21"
---

# Cannot use import statement outside a module을 브라우저와 Node.js에서 해결하기

`SyntaxError: Cannot use import statement outside a module`은 파일이 클래식 스크립트나 CommonJS로 실행됐다는 뜻이에요. 모듈로 불러오면 같은 `import`가 실행돼요.

Chrome 157, Safari 27.2, Node.js 22.18.0 및 @logbrew/browser 0.1.22 환경에서 2026년 11월 21일에 테스트

글 [Furkan Erday](https://github.com/furkanerday). LogBrew 창업자 Furkan Erday. 매일 Claude Code와 Codex로 LogBrew를 만들어요.

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

## script 태그 5개가 `import` 1개를 어떻게 처리했는지

| 페이지가 불러온 방식 | 코드 실행 | 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만 하는 파일을 클래식 태그로 불러오면 첫 `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 추가하기

같은 태그에 `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에서 모듈 type 설정하기

`package.json`에 `"type": "module"`을 넣거나 파일 이름을 `.mjs`로 바꾸세요. 두 방법 모두 경고 없이 파일을 실행했어요. Node.js는 `type` 필드 값과 관계없이 `.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년에 `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는 구문 분석 오류를 `Browser error: SyntaxError`라는 이슈 1개로, 그룹화 키 `browser.error:SyntaxError`와 함께 기록했어요. 이슈에는 파일 경로와 줄이 있고 스택 프레임은 없으며, 메시지는 `redacted`였어요. SDK가 오류 메시지를 보내지 않기 때문이에요.

두 브라우저의 import 오류와 export 오류는 모두 그 이슈 1개로 모였어요. 키에 오류 타입만 들어 있기 때문이에요. 어느 파일을 고칠지는 `sourcePath`로 알 수 있어요. 다른 출처의 스크립트는 줄이 0이고 파일 경로가 없는 별도 이슈 `Browser error: Error`가 됐어요.

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.`를 표시했어요. 같은 문제이고 해결법도 같아요.

### Unexpected token export는 무슨 뜻인가요?

클래식 스크립트에서는 `export`도 쓸 수 없어요. Chrome은 `Unexpected token 'export'`, Safari는 `Unexpected keyword 'export'`를 표시했어요. 그 파일도 모듈로 불러오세요.

## 구문 분석에 실패한 스크립트를 모두 확인

LogBrew 브라우저 SDK는 구문 분석 오류를 파일과 줄과 함께 기록하고 오류 타입별로 묶어요. 넉넉한 무료 요금제로 시작하세요. 카드 등록은 필요 없어요.

[무료로 시작](https://logbrew.co/ko)

## 출처

- [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)

## 오류 해결법 더 보기

- [메시지와 파일, 줄을 숨기는 스크립트 오류 Script error 해결하기](https://logbrew.co/ko/errors/script-error)
- [Failed to fetch 오류를 고치고 원인 3가지를 구분하는 방법](https://logbrew.co/ko/errors/failed-to-fetch)
- [Kotlin과 Android의 java.lang.NullPointerException을 메시지로 해결하기](https://logbrew.co/ko/errors/nullpointerexception)
- [Minified React error #418과 #185를 전체 메시지와 내 코드 줄로 해결하기](https://logbrew.co/ko/errors/minified-react-error)
- [AxiosError Network Error 해결하고 3가지 원인 중 어느 것인지 찾기](https://logbrew.co/ko/errors/axios-network-error)
- [HTTP 499 오류를 해결하고 누가 먼저 기다리기를 멈췄는지 찾기](https://logbrew.co/ko/errors/http-499)
- [직접 재현한 오류와 각각의 해결법](https://logbrew.co/ko/errors)
