TypeScript(tsc)でディレクトリ指定のみでindex.tsをimportするときはmoduleResolutionをnodeにする
created:
「ディレクトリ指定のみでindex.tsをimportする」とは下記を想定しています。
import foo from './foo'
// import foo from './foo/index' の省略形
関連付いたモジュールを一つのindex.tsにまとめてimportしておくと便利ですが、この手法のことをBarrelというそうです。
Barrel - TypeScript Deep Dive 日本語版
以下、node v12.13.0、npm v6.12.0、typescript v3.6.4で検証しました。
npm init
やtypescriptパッケージのインストール後、プロジェクトのルートにtsconfig.json
を作成します(今回の内容は適当です)。
{
"compilerOptions": {
"outDir": "./dist",
"target": "es5",
"module": "es6",
"strict": true,
"esModuleInterop": true
},
"include": [
"./src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
package.json
にscriptsを設定しておきましょう。
{
...
"scripts": {
"build": "tsc"
}
...
}
その後、下記の2ファイルを作成してみます。
// /src/modules/index.ts
export default function func () {
return 'foo'
}
// /src/index.ts
import func from './modules'
func()
作成したら、buildしてみます。
npm run build
すると、下記のようなエラーが出てしまいます。
src/index.ts:3:18 - error TS2307: Cannot find module './modules'.
このエラーはtsconfig.json
に下記を追記することで解消できます。
{
"compilerOptions": {
...
"moduleResolution": "node", // 追加
...
}
}