1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScript で subpath export されたモジュールを import しようとすると `TS2307 Cannot find module` エラーになる問題の解決

Last updated at Posted at 2022-08-17

概要

package.json の exports 記法 (Modules: Packages | Node.js v18.7.0 Documentation) でエクスポートされた subpath モジュールを、 TypeScript 4.7.4 で import しようとすると、次のようなエラーになる。

import.ts:1:19 - error TS2307: Cannot find module 'exporter/foo' or its corresponding type declarations.

1 import {FOO} from 'exporter/foo'
                    ~~~~~~~~~~~~~~

問題の再現

1. import 対象のパッケージ(exporter)の作成

package.json の exports で import ... from 'exporter/foo' として import できるパッケージを作成してみる。


mkdir exporter
cd exporter

cat > package.json <<'EOS'
{
  "name": "exporter",
  "version": "1.0.0",
  "exports": {
    "./foo": {
      "import": {
        "types": "./dist/foo.d.ts",
        "default": "./dist/foo.js"
      }
    }
  }
}
EOS

cat > tsconfig.json <<'EOS'
{
  "compilerOptions": {
    "declaration": true,
    "outDir": "./dist",
    "rootDir": "./src",
  },
}
EOS

mkdir src
cat > src/foo.ts <<'EOS'
const FOO = 123
export {FOO}
EOS

npm i -D typescript
./node_modules/.bin/tsc

2. import 側のコードを作成

exporter/foo を import するコードを書く。

mkdir importer
cd importer

# 下の「4. Node.js で直接実行してみる」のための設定
cat > "package.json" <<'EOS'
{
  "type": "module"
}
EOS

npm i -D typescript ../exporter

cat > import.ts <<'EOS'
import {FOO} from 'exporter/foo'

console.log(FOO)
EOS

3. コンパイル

exporter/foo を TypeScript は見つけられない。

$ ./node_modules/.bin/tsc import.ts

import.ts:1:19 - error TS2307: Cannot find module 'exporter/foo' or its corresponding type declarations.

1 import {FOO} from 'exporter/foo'
                    ~~~~~~~~~~~~~~

4. Node.js で直接実行してみる

こちらは問題ない。

$ cp import.ts as-plainjs.js
$ node as-plainjs.js
123

解決方法

typescript-subpath-exports-workaround - npm

を参考に、 typesVersions の記述を exporter の package.json に導入する。

{
  "name": "exporter",
  "version": "1.0.0",
  "exports": {
    "./foo": {
      "types": "./dist/foo.d.ts",
      "import": "./dist/foo.js"
    }
  },
  "typesVersions": {  // <=== 追加
    "*": {
      "foo": ["dist/foo"]
    }
  }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?