For

2023.12.30

Pothos + GraphQL Code Generatorでrequire('string-width')がERR_REQUIRE_ESMになったら試すこと

概要

Pothos + GraphQL Code Generatorで環境構築を行う際に、以下のようなエラーが出る場合があります。

bash_____terminal_____root@b1f08b263a24:/workspace# yarn graphql-codegen
yarn run v1.22.19
$ /workspace/node_modules/.bin/graphql-codegen
/workspace/node_modules/cliui/build/index.cjs:291
const stringWidth = require('string-width');
                                   ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /workspace/node_modules/string-width/index.js from /workspace/node_modules/cliui/build/index.cjs not supported.
Instead change the require of index.js in /workspace/node_modules/cliui/build/index.cjs to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/workspace/node_modules/cliui/build/index.cjs:291:21) {
        code: 'ERR_REQUIRE_ESM'
    }


関連モジュールのバージョンを固定することで解消できるため、以下のように固定します。

対応

package.jsonを更新

package.json に以下のように resolutions プロパティを追加します。

JSON_____package.json_____  "resolutions": {
    "jackspeak": "2.1.1"
  }


モジュール削除 & yarn

yarn.locknode_modules を削除して yarn します。
これで上記でresolutionsに追記したパッケージのバージョンが固定され、概要に記載されたエラーを解消できます。