はじめに
Next.jsでContentfulの型定義ファイルを自動生成する際にエラーが出たので対処法をメモします。
問題
contentful-typescript-codegenのライブラリを使って型定義ファイルを生成するコマンドを実行した際に、以下のエラーが発生しました。
% npm run contentful-typescript-codegen
> nextjs-media-skeleton-template@0.1.0 contentful-typescript-codegen
> contentful-typescript-codegen --output @types/generated/contentful.d.ts
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /hoge/getContentfulEnvironment.ts
require() of ES modules is not supported.
require() of /hoge/getContentfulEnvironment.ts from /hoge/node_modules/contentful-typescript-codegen/dist/contentful-typescript-codegen.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from /hoge/package.json.
エラー内容に書いてある通り、ESモジュールをロードするにはimportを使用する必要があり、require()はサポートされていません。getContentfulEnvironment.tsファイルを確認すると、requireを使用していました。
・getContentfulEnvironment.ts
const contentfulManagement = require('contentful-management')
const getContentfulEnvironment = () => {
const contentfulClient = contentfulManagement.createClient({
accessToken: 'xxxxxxxxx',
})
return contentfulClient
.getSpace('xxxxxxxxx')
.then((space: { getEnvironment: (arg0: string) => any }) => space.getEnvironment('xxxxxx'))
}
module.exports = getContentfulEnvironment
解決方法
エラーメッセージに「Instead change the requiring code to use import(), or remove "type": "module"」とある通り、importに変えるかpackage.jsonで指定している"type": "module"を削除することで解決できました。
おわりに
ESモジュールが主流になっているとはいえ、CommonJSについても知ってく必要がありそうです。