This module can only be referenced with ECMAScript imports/exports
TypeScriptでCommonJSとESModulesの相互運用設定が必要な場合のエラー
概要
TypeScriptでCommonJSモジュールをESModules形式(import/export)でインポートする際に、esModuleInteropやallowSyntheticDefaultImportsの設定が必要な場合に発生するエラーです。
エラーメッセージ
This module can only be referenced with ECMAScript imports/exports by turning on the 'esModuleInterop' flag and referencing its default export.
Module 'xxx' has no default export.
Cannot find module 'xxx' or its corresponding type declarations.
原因
- esModuleInterop未設定: CommonJSモジュールをESM形式でインポート
- デフォルトエクスポートなし:
module.exportsをデフォルトインポートで取得 - 型定義の不一致: @typesパッケージとモジュール本体の不整合
- Node.jsモジュール解決: ESMとCJSの混在
解決策
1. tsconfig.jsonで設定
| |
2. インポート形式を修正
| |
3. CommonJSスタイルのインポート
| |
4. 名前付きエクスポートを使用
| |
5. Node.js ESMモードの設定
| |
| |
6. 型定義のインストール
| |
| |
7. 動的インポート
| |
8. Babelとの連携
| |
esModuleInteropの動作
| |
推奨設定
| |
よくある間違い
import * asとimport defaultを混同する- @typesパッケージのバージョンが古い
- Node.jsとブラウザで異なるモジュール解決を使う
関連エラー
参考リンク
TypeScript の他のエラー
この記事は役に立ちましたか?