GrepBoard/매뉴얼
605 편 ·

Node Cannot use import statement 오류 해결

·시험 환경 Node.js 18.20.8 · 20.20.2 · 22.23.4 · 24.22.1 (Docker node:*-slim) · 2026-10·시험 범위 ↓·5 단계

Cannot use import statement outside a module 은 파일이 CommonJS 로 읽힌 것입니다. type 과 Node 판으로 가르고 ERR_REQUIRE_ESM 도 고칩니다.

output
/srv/app/app.js:1import { hello } from './lib.mjs';^^^^^^ SyntaxError: Cannot use import statement outside a module

Cannot use import statement outside a module 는 import 가 들어 있는 파일을 Node.js 가 CommonJS 로 읽었다는 뜻입니다. 가장 가까운 package.json 에 "type": "module" 을 넣거나 파일을 .mjs 로 바꾸면 ES 모듈로 읽습니다. 다만 같은 파일이라도 Node 판과 type 값에 따라 결과가 달라서, 먼저 어느 경우인지 봅니다.

[1] Node 판과 가장 가까운 package.json 의 type 을 확인합니다.

console
$ node -v$ npm pkg get type

같은 app.js(import 한 줄)를 네 판의 공식 이미지에서 돌린 결과입니다.

조건18.20.820.20.2 · 22.23.4 · 24.22.1
package.json 없음SyntaxError실행됨
type 없는 package.jsonSyntaxError실행됨 + 경고
"type": "commonjs"SyntaxErrorSyntaxError
"type": "module"실행됨실행됨

공식 문서의 「Syntax detection」은 22.7.0 부터 기본으로 켜져, type 이 없으면 문법을 보고 ES 모듈로 다시 읽습니다(20.20.2 도 같게 동작했습니다). 그래서 지금 판에서 이 오류가 나면 거의 "type": "commonjs" 가 적힌 경우이거나 Node 18 같은 옛 판입니다. type 이 없는 package.json 에서는 22 에서 이런 경고가 붙었습니다.

output
hello from lib.mjs(node:31) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///srv/app/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 /srv/app/package.json.

[2] 프로젝트 전체가 import 를 쓰면 type 을 module 로 바꿉니다.

console
$ npm pkg set type=module; grep -n type package.json
output
12:  "type": "module"

이 값은 그 package.json 아래 모든 .js 에 걸립니다. require()·module.exports·__dirname 을 쓰는 .js 가 남아 있으면 이번에는 반대 오류가 납니다.

output
ReferenceError: require is not defined in ES module scope, you can use import insteadThis file is being treated as an ES module because it has a '.js' file extension and '/srv/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

그런 파일은 메시지대로 .cjs 로 이름을 바꿉니다. 바꿀 파일이 많으면 거꾸로 type 은 두고 import 를 쓰는 파일만 .mjs 로 바꾸는 편이 범위가 작습니다. 되돌리려면 npm pkg delete type(원래 commonjs 였다면 npm pkg set type=commonjs)입니다.

[3] CommonJS 파일에서 ES 모듈을 require() 하다가 ERR_REQUIRE_ESM 이 나면 Node 판부터 봅니다. Node 18 에서는 이렇게 막힙니다.

output
Error [ERR_REQUIRE_ESM]: require() of ES Module /srv/app/lib.mjs not supported.Instead change the require of /srv/app/lib.mjs to a dynamic import() which is available in all CommonJS modules.

같은 main.cjs 가 20.20.2 · 22.23.4 · 24.22.1 에서는 그대로 돌았습니다. 공식 문서 기준으로 require() 로 ES 모듈을 읽는 기능은 22.12.0 과 20.19.0 에서 플래그 없이 켜졌습니다. 다만 20.x 도 18.x 처럼 이미 지원이 끝났으므로(20.x 는 2026-04-30 · Node.js 릴리스 일정), ESM 전용 패키지 때문에 이 오류가 나면 지원 중인 Node 22 나 24 의 최신 패치판으로 올리는 것이 가장 짧은 길입니다. 판을 고를 수 없어 기능만 확인한다면 경계는 20.x 에서 20.19.0, 22.x 에서 22.12.0 입니다(21.x 와 22.0~22.11 에서는 기본으로 켜져 있지 않습니다). 올릴 수 없으면 [5] 의 import() 를 씁니다.

[4] 새 판에서 ERR_REQUIRE_ASYNC_MODULE 이 나면 읽으려는 모듈(또는 그 모듈이 가져오는 모듈)에 최상위 await 가 있는 것입니다.

output
Error [ERR_REQUIRE_ASYNC_MODULE]: require() cannot be used on an ESM graph with top-level await. Use import() instead. To see where the top-level await comes from, use --experimental-print-required-tla.

이것은 판을 올려도 풀리지 않습니다. 문서도 이 경우 import() 를 쓰라고 적습니다. 어느 파일의 await 인지 모르면 메시지에 나온 --experimental-print-required-tla 를 붙여 한 번 돌립니다.

[5] CommonJS 에 남아야 하는 코드는 동적 import() 로 바꿉니다. 모든 판에서 됩니다.

main-dyn.cjs
import('./tla.mjs').then((m) => console.log(m.default));
console
$ node main-dyn.cjs
output
tla

import() 는 Promise 를 돌려주므로 그 값을 쓰는 코드는 then 안이나 async 함수 안으로 옮깁니다. 기본 내보내기는 m.default 로 꺼냅니다.

설치 단계에서 나는 npm 오류는 npm ERR! code ERESOLVE와 npm install -g EACCES를 봅니다.

#nodejs#esm#commonjs#err-require-esm