问题描述
Next.js 最近做了一个修改(在 v11.0.x 中),它具有以下类型定义:
Next.js has recently made a modification (in v11.0.x) which has the following type definitions:
在 next-env.d.ts
中(不可修改,在每次构建时重新生成):
In next-env.d.ts
(non-modifiable, regenerated at every build):
/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
在node_modules/next/image-types/global.d.ts
(不可修改,不想使用patch-package
):
In node_modules/next/image-types/global.d.ts
(non-modifiable, don't wanna use patch-package
):
declare module '*.svg' {
const content: any
export default content
}
现在的问题是我正在使用 @svgr/webpack
,因此我需要执行以下操作:
Now the issue is that I am using @svgr/webpack
, and as a result I need to do the following:
declare module '*.svg' {
const content: React.FC<React.SVGAttributes<SVGElement>>
export default content
}
之前将此代码放在用于工作的资产文件夹中的 index.d.ts
中.但现在它没有了,因此我被迫单独转换每个导入.有什么方法可以直接做到这一点?
Earlier placing this code in index.d.ts
in the assets folder used to work. But now it doesn't and as result I am forced to cast every import separately. Any way to do this directly?
推荐答案
我正在使用以下解决方法:
I am using the following workaround:
在
tsconfig.json
中添加next-env.d.ts
排除数组:
{
// ...
"exclude": ["node_modules", "next-env.d.ts"]
}
将 next-env.d.ts
添加到 .gitignore
/.eslintignore
.
创建新文件custom.d.ts
:
/// <reference types="next" />
/// <reference types="next/types/global" />
// additional things that one used to put here before Next.js v11
创建新文件images.d.ts
:
type StaticImageData = {
src: string;
height: number;
width: number;
placeholder?: string;
};
declare module '*.png' {
const content: StaticImageData;
export default content;
}
declare module '*.svg' {
const content: React.FC<React.SVGProps<SVGSVGElement>>;
export default content;
}
declare module '*.jpg' {
const content: StaticImageData;
export default content;
}
declare module '*.jpeg' {
const content: StaticImageData;
export default content;
}
declare module '*.gif' {
const content: StaticImageData;
export default content;
}
declare module '*.webp' {
const content: StaticImageData;
export default content;
}
declare module '*.ico' {
const content: StaticImageData;
export default content;
}
declare module '*.bmp' {
const content: StaticImageData;
export default content;
}
确保这些文件由 tsconfig
的 include
数组中指定的模式处理.
Make sure that these files are handled by patterns specified in include
array of tsconfig
.
如果您在 next@12
中使用 *.avif
,也请添加声明:
Add declarations for *.avif
too if you're using them in next@12
:
declare module '*.avif' {
const content: StaticImageData
export default content
}
这篇关于如何覆盖 Next.js `*.svg` 模块声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!