Next.js 13中TypeScript d.ts文件导入失败问题排查求助
问题分析与解决方案
问题根源
你的global.d.ts文件中包含了export语句,这使得它从环境类型声明文件变成了模块类型文件。而Next.js默认的模块解析逻辑(基于webpack)不会自动将.d.ts作为可导入的扩展名——这类文件原本设计用于提供类型信息,而非包含可执行的运行时代码,因此解析器不会主动识别它作为模块文件。
解决方案
方案一:分离类型声明与运行时变量(推荐)
将类型定义和实际的常量值分开,符合TypeScript的最佳实践:
- 修改
types/global.d.ts,仅保留类型声明:
declare module "*.svg" { import React = require("react"); export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; const content: string; export default content; } declare module "*.png" { const value: string; export default value; } declare module '*.module.css' { const styles: { [className: string]: string }; export default styles; } // 仅添加类型定义,不导出实际值 export type CurrencyLocaleType = Record<string, string>; export type LocaleMappingType = Record<string, string>;
- 在
types目录下新建global.ts文件,存放实际的常量:
import type { CurrencyLocaleType, LocaleMappingType } from './global'; export const CurrencyLocale: CurrencyLocaleType = { de: "EUR", en: "EUR", }; export const LocaleMapping: LocaleMappingType = { de: "de-DE", en: "en-EN", };
- 正常导入使用:
import { CurrencyLocale, LocaleMapping } from "@/types/global";
方案二:配置Next.js解析.d.ts扩展名
如果需要保留在.d.ts文件中导出常量的写法,可以修改Next.js的webpack配置,让它识别.d.ts作为模块扩展名:
- 在项目根目录创建或修改
next.config.js:
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { // 添加.d.ts到可解析扩展名列表 config.resolve.extensions.push('.d.ts'); return config; }, }; module.exports = nextConfig;
- 确保
tsconfig.json的include字段已经包含types/**/*.d.ts(你的配置已经满足)。
额外优化:调整tsconfig路径配置
你的@/*路径映射中./types/*是冗余的,因为@/types/*已经单独配置了,可以简化为:
"paths": { "@/*": ["./*"], "@/types/*": ["./types/*", "./app/types/*"] }
内容的提问来源于stack exchange,提问作者fefe
相关产品推荐
相关产品推荐

