我正试图将我的简历.pdf文件添加到我的投资组合网站,目标是该文件一旦被点击就可以下载.我将.pdf文件和一个tyes.s.ts文件夹添加到了src文件夹中.

我将pdf文件导入到Resume.tsx组件中:

import resumePDF from "../src/Resume.pdf";

下载按钮:

<a href={resumePDF}>
    <button id="resume-button">Download Resume</button>
</a> 

我在上面的代码中遇到以下错误:

ERROR in src/Resume.tsx:2:23
TS2307: Cannot find module '../src/Resume.pdf' or its corresponding type declarations.
    1 | import React from "react";
  > 2 | import resumePDF from "../src/Resume.pdf";
      |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    3 |
    4 | function Resume() {
    5 |   return (

当我转到tyes.s.ts文件时,我看到以下错误:

ERROR in src/types.s.ts:1:16
TS2664: Invalid module name in augmentation, module '*.pdf' cannot be found.
  > 1 | declare module "*.pdf";
      |                ^^^^^^^
    2 |
    3 | export default module;
    4 |

根据我所阅读的内容,我应该将EXPORT添加到tyes.s.ts文件的底部,但我不确定在这里还应该添加什么.

推荐答案

1-您需要使用以下命令安装types/node:

npm i --save-dev @types/node

2-将您的pdf放入Reaction默认创建的公用文件夹中:

put your pdf in the public folder that React creates by default

3-在src文件夹中创建types.s.ts个文件:

function getPDFURL(pdfFile: string): string {
    return pdfFile;
  }
export default getPDFURL;

4-在要添加下载按钮的组件中:

//import first:
import  pdf  from "./types.s";

// then create resumePDF using pdf function:
const resumePDF = pdf("Resume.pdf");

//finally use resumePDF in your jsx:
<a href={resumePDF}>
      <button id="resume-button">Download Resume</button>
</a>

Note:如果您希望用户下载pdf而不是打开它,您可以将download属性添加到a标记,如下所示:

<a href={resumePDF} download>
  <button id="resume-button">Download Resume</button>
</a>

Typescript相关问答推荐

为什么缩小封闭内部不适用于属性对象,但适用于声明的变量?

忽略和K的定义

APIslice-CreateAPI的RTK打字错误

从子类构造函数推断父类泛型类型

使用Dockerfile运行Vite React应用程序时访问env变量

TS如何不立即将表达式转换为完全不可变?

如何编写在返回函数上分配了属性的类型安全泛型闭包

如何将父属性类型判断传播到子属性

使用泛型识别对象值类型

带投掷的收窄类型

如何将通用接口的键正确设置为接口的键

如何创建内部和外部组件都作为props 传入的包装器组件?

类型脚本中参数为`T`和`t|unfined`的重载函数

如何处理可能为空的变量...我知道这不是Null?

如何在Vue动态类的上下文中解释错误TS2345?

为什么类方法参数可以比接口参数窄

如何让Record中的每个值都有独立的类型?

覆盖高阶组件中的 prop 时的泛型推理

Angular另一个组件的nativeelement未定义

元素隐式具有any类型,因为string类型的表达式不能用于索引类型{Categories: Element;管理员:元素; }'