はじめに
モジュール ‘./utils/calcTotalTime.js’ の宣言ファイルが見つかりませんでした のエラーについてまとめました。
問題
ReactとTypeScriptの環境で、jsファイルでUtilを作成し、tsxファイルにインポートしたら表題のエラーが発生しました。
// ~/<ProjectName>/src/App.tsx
import { calcTotalTime } from './utils/calcTotalTime.js';
export const App = () => {
const totalTime = calcTotalTime(records); // モジュール ‘./utils/calcTotalTime.js’ の宣言ファイルが見つかりませんでした。
// ...
};
// ~/<ProjectName>/src/utils/calcTotalTime.js
export function calcTotalTime (records) {
const totalTime = records
.map((record) => record.time)
.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
return totalTime;
}
解決方法
tsxファイルではデフォルトで jsファイルをインポートできないため、tsconfig.app.json の compilerOptions で “allowJs”: true のオプションを追加することで解決できました。
// ~/<ProjectName>/tsconfig.app.json
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"allowJs": true // ← 追加したオプション
},
"include": ["src"]
}
おわりに
tsconfig.json の役割や何ができるかも学習していきたいと思います。
参考
