MeWrite Docs

SyntaxError: Cannot use import statement outside a module

CommonJS環境でESMのimport文を使用した際に発生するSyntaxError

概要

SyntaxError: Cannot use import statement outside a module は、ES Modules(ESM)の import 構文をCommonJS環境で使用した際に発生するエラーです。Node.jsはデフォルトでCommonJSモジュールシステムを使用するため、ESM構文を使うには明示的な設定が必要です。

エラーメッセージ

SyntaxError: Cannot use import statement outside a module
(node:12345) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs file extension.
SyntaxError: Cannot use import statement outside a module

原因

  1. package.jsonに"type": “module"が未設定: Node.jsがファイルをCommonJSとして解釈している
  2. ファイル拡張子が.jsのまま: ESMとして認識されない
  3. TypeScriptのtsconfig設定不足: moduleオプションが適切でない
  4. Jestなどテストランナーの設定不足: テスト環境でESMが未対応
  5. CDN/scriptタグでtype=“module"が未指定: ブラウザ環境での設定漏れ

解決策

1. package.jsonに"type”: “module"を追加

1
2
3
4
5
6
7
8
{
  "name": "my-project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  }
}
1
2
3
// これでimport文が使える
import express from "express";
import { readFile } from "fs/promises";

2. ファイル拡張子を.mjsに変更

1
2
3
# package.jsonを変更せずにESMを使いたい場合
mv index.js index.mjs
node index.mjs
1
2
3
4
5
6
7
// index.mjs - ESMとして認識される
import path from "path";
import { fileURLToPath } from "url";

// ESMでは__dirnameが使えないため代替手段を使う
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

3. TypeScriptのtsconfig.json設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2020",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "outDir": "./dist"
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Node.js向けの場合(ts-nodeやtsxで実行)
{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "esModuleInterop": true,
    "outDir": "./dist"
  }
}

4. CommonJS構文に書き換える

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// ESM構文(エラーになる場合)
import express from "express";
import { join } from "path";

// CommonJS構文に変換
const express = require("express");
const { join } = require("path");

// default exportの場合
// import config from "./config.js";
const config = require("./config.js");

5. Jestでの設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// jest.config.js
export default {
  // ESMサポートを有効化
  transform: {},
  extensionsToTreatAsEsm: [".ts"],

  // TypeScript + ESMの場合
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        useESM: true,
      },
    ],
  },
};
1
2
# 実行時にESMフラグを指定
node --experimental-vm-modules node_modules/.bin/jest

6. ブラウザ環境での対応

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!-- ❌ エラー: type="module"がない -->
<script src="app.js"></script>

<!-- ✅ ESMとして読み込む -->
<script type="module" src="app.js"></script>

<!-- ✅ インラインでも使用可能 -->
<script type="module">
  import { greet } from "./utils.js";
  greet("World");
</script>

関連エラー

JavaScript の他のエラー

最終更新: 2026-02-03