无.d.ts的JS模块在TypeScript中智能提示失效的解决方法
问题
在通过pnpm dlx create-next-app@latest搭建的Next.js TypeScript项目中,使用无.d.ts文件的JavaScript模块时,JS文件能正常触发智能提示,但TS文件无法获取类型提示。示例JS模块代码如下:
// ./test1.js module.exports = { data1: "hehe", data2: Math.PI, func1: function() { return "hello, world!"; } };
真实项目依赖无TypeScript支持、无活跃维护的老旧JS模块,希望通过配置让TypeScript自动识别这些JS模块的类型,无需手动编写.d.ts文件。当前项目的tsconfig.json和package.json配置如下:
tsconfig.json
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
package.json
{ "name": "nextjs_sample_page", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@types/node": "20.3.1", "@types/react": "18.2.13", "@types/react-dom": "18.2.6", "eslint": "8.43.0", "eslint-config-next": "13.4.7", "next": "13.4.7", "react": "18.2.0", "react-dom": "18.2.0", "typescript": "5.1.3", "wrtc": "^0.4.7" } }
解决方案
要实现TypeScript自动推断无.d.ts的JS模块类型,需调整tsconfig.json的关键配置:
- 扩展
include范围,纳入JS文件
当前include仅包含TS/TSX文件,TypeScript无法读取JS模块内容进行类型推断。将**/*.js和**/*.jsx加入include数组:
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"]
- 开启
allowSyntheticDefaultImports(针对CommonJS模块)
对于使用module.exports导出的JS模块(如示例中的test1.js),开启该配置可配合esModuleInterop优化CommonJS模块的导入兼容性,提升类型推断准确性。在compilerOptions中添加:
"allowSyntheticDefaultImports": true
- 按需关闭
isolatedModulesisolatedModules要求每个文件独立为模块,可能限制TypeScript对JS模块的类型推断能力。若上述配置后仍无提示,可尝试将其设为false:
"isolatedModules": false
修改配置后,重启TypeScript语言服务(或编辑器),TS文件中导入该JS模块即可获得自动推断的智能提示。
内容的提问来源于stack exchange,提问作者Farhan M Sabran
相关产品推荐
相关产品推荐

