Node.jsのCannot use importエラーの直し方
ターミナルで node index.js を実行したときに SyntaxError: Cannot use import statement outside a module が出るのは、import 文を書いたファイルを、Node.js が CommonJS(require を使う、Node.js に元からある形式)のファイルとして読んだときです。package.json に "type": "module" を書くか、ファイルの拡張子を .mjs にすると、ES モジュールとして読まれてエラーが消えます。
npm init -y でプロジェクトを作り、import を書いたスクリプトをすぐ実行したときにも出ます。Node.js 24 に付いてくる npm 11(検証では 11.19.1)の npm init -y は、package.json に "type": "commonjs" を書くからです。私は検証環境でエラーを起こし、メッセージの全文と、直すと消えることを確かめました。
検証環境は Ubuntu 24.04 です。主に Node.js 24.22.2(npm 11.19.1)で試し、比べるために Node.js 22.23.4(npm 10.9.9)と Node.js 20.18.3 でも同じファイルを実行しました。Node.js 24 と 20.18 は、nodejs.org で配布されている Linux 用のバイナリを使いました。Windows と macOS、TypeScript のファイル(.ts)を直接実行する場合、Jest や webpack などのツールの中で出る同じ名前のエラー、ブラウザーで出る同じ名前のエラーは試していません。
エラーの全文
検証環境(Ubuntu 24.04、Node.js 24.22.2)で、空のフォルダーで npm init -y を実行すると、次の package.json ができました。最後の行に "type": "commonjs" があります。
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
同じフォルダーに、import でファイルを読む関数を取り込む index.js を置きました。中身は、message.txt(「hello」とだけ書いたファイル)を読んで表示するだけです。
import { readFileSync } from 'node:fs';
const text = readFileSync('./message.txt', 'utf8');
console.log(text.trim());
node index.js を実行すると、次のように出て止まりました(終了コードは1。パスは例示用の値に置き換えています)。
$ node index.js
(node:1287) Warning: Failed to load the ES module: /path/to/app/index.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/path/to/app/index.js:1
import { readFileSync } from 'node:fs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1861:18)
at Module._compile (node:internal/modules/cjs/loader:1903:20)
at Object..js (node:internal/modules/cjs/loader:2060:10)
at Module.load (node:internal/modules/cjs/loader:1651:32)
at Module._load (node:internal/modules/cjs/loader:1443:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:261:19)
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
at node:internal/main/run_main_module:33:47
Node.js v24.22.2
エラー本体は SyntaxError: Cannot use import statement outside a module の行で、「モジュールの外では import 文は使えない」という意味です。ここでいうモジュールは ES モジュールのことで、このファイルは ES モジュールとして扱われていない、ということです。その上の /path/to/app/index.js:1 と ^^^^^^ が、どのファイルの何行目の import で止まったかを示しています。スタックには cjs/loader(CommonJS の読み込み処理)の名前が並んでいます。
いちばん上の Warning: の行には、直し方がそのまま書かれています。「いちばん近い package.json に "type": "module" を書くか、拡張子を .mjs にしてください」という意味です。
Node.js がファイルの形式を決める順番
Node.js は、.js のファイルを CommonJS と ES モジュールのどちらとして読むかを、ファイルの中身より先に、拡張子と package.json で決めます。公式ドキュメントにある、モジュールの形式の決め方の説明と、検証の結果をまとめると、次のとおりです。
| ファイル | 読まれ方 | import を書いたときの結果(Node.js 24) |
|---|---|---|
.mjs |
必ず ES モジュール | 動く |
.cjs |
必ず CommonJS | エラー("type": "module" があっても) |
.js、package.json に "type": "module" |
ES モジュール | 動く |
.js、package.json に "type": "commonjs" |
CommonJS | エラー |
.js、package.json に type がない |
中身を見て決める | 警告が出るが動く |
import を書いたのにエラーになるのは、表の「エラー」の行に当たるときです。つまり、拡張子が .cjs か、package.json に "type": "commonjs" があるときです。.cjs のファイルでは、package.json を "type": "module" にしていても、同じエラーが出ました。
type を書かない場合の動きは、Node.js のバージョンで変わります。これは次の節で説明します。
直し方とエラーが消えたこと
直し方は3つあります。どれも、同じ処理をするファイルでエラーが消えることを確かめました。
package.json の type を module にする
これから import で書いていくなら、この方法が素直です。package.json の "type" を "module" に書き換えます。手で編集してもよく、npm pkg set でも変えられます。
$ npm pkg set type=module && grep '"type"' package.json
"type": "module"
$ node index.js
hello
エラーも警告も出ず、message.txt の中身が表示されました。公式ドキュメントの "type" の説明によると、この設定は、その package.json を「いちばん近い親」とするすべての .js ファイルに効きます。フォルダーをさかのぼって最初に見つかった package.json が使われるので、上の階層にある package.json を書き換えても、より近い package.json のほうが使われます。
ファイルの拡張子を .mjs にする
package.json を変えたくないときや、CommonJS のプロジェクトの中で1つのファイルだけ ES モジュールにしたいときは、拡張子を .mjs にします。package.json を "type": "commonjs" に戻したまま、中身が同じ index.mjs を実行しました。
$ cp index.js index.mjs && node index.mjs
hello
index.js のほうは同じエラーのままで、index.mjs だけが動きました。
require に書き換えて CommonJS のまま使う
プロジェクト全体が CommonJS で、ほかのファイルが require を使っているなら、import を require に書き換えるのも手です。
const { readFileSync } = require('node:fs');
const text = readFileSync('./message.txt', 'utf8');
console.log(text.trim());
"type": "commonjs" のまま、この index-cjs.js を実行すると、エラーは出ずに hello と表示されました。
type を書かない場合は Node.js のバージョンで結果が変わる
package.json から type の行を消して(npm pkg delete type)、同じ index.js を3つのバージョンで実行しました。
Node.js 24.22.2 と 22.23.4 では、どちらも hello と表示され、同じ文面の警告が出ました(表示の順番は、22 では hello が先でした)。次は Node.js 24.22.2 の出力です(パスは例示用の値に置き換えています)。
(node:1416) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///path/to/app/index.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 /path/to/app/package.json.
(Use `node --trace-warnings ...` to show where the warning was created)
「形式が指定されておらず、CommonJS として読めなかったので、ES モジュールとして読み直した。そのぶん遅くなる」という意味です。これは公式ドキュメントにある構文の検出(Syntax detection)という仕組みで、Node.js 22.7.0 と 20.19.0 から、何も指定しなくても有効になっています。
一方、Node.js 20.18.3 では、同じファイルで SyntaxError: Cannot use import statement outside a module が出て止まりました。この版はまだ構文の検出が既定で有効になっていないため、type がない .js は CommonJS として読まれます。古い Node.js では、type を書かないだけでもこのエラーになります。
新しい Node.js なら type がなくても動きますが、毎回警告が出ます。公式ドキュメントも、CommonJS だけのパッケージでも type を書いておくことを勧めています。import を使うなら "type": "module" を書いておくのが確実です。
Node.js 22.23.4 に付いてくる npm 10.9.9 の npm init -y は、type の行を書きませんでした。同じ手順でも、npm 10.9.9 で作ったプロジェクトは「警告が出るが動く」、npm 11.19.1 で作ったプロジェクトは「エラーで止まる」と、結果が分かれます。npm 11.19.1 で npm config get init-type を実行すると commonjs と出ます。npm の設定の説明でも、init-type の既定値は "commonjs" です。
type を module にしたあとに出る require のエラー
"type": "module" にして import のエラーが消えても、同じファイルに require が残っていると、今度は別のエラーが出ます。import と require を1行ずつ書いた mixed.js を実行すると、次のように出ました(パスは例示用の値に置き換えています)。
import { readFileSync } from 'node:fs';
const path = require('node:path');
console.log(path.basename('./message.txt'), readFileSync('./message.txt', 'utf8').trim());
$ node mixed.js
file:///path/to/app/mixed.js:2
const path = require('node:path');
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/path/to/app/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///path/to/app/mixed.js:2:14
at ModuleJob.run (node:internal/modules/esm/module_job:561:25)
at async node:internal/modules/esm/loader:647:26
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v24.22.2
ES モジュールの中では require は使えません(公式ドキュメントの、ES モジュールと CommonJS の違い)。type を module にしたら、そのファイルの require も import に書き換えます。この例では、2行目を import path from 'node:path'; にすると、エラーは出ずに message.txt hello と表示されました。





