我正在尝试导入图像以在TypeScript的React组件中使用。我正在使用的捆绑器是包裹(不是Webpack)。
我已经在.d.ts项目内部创建了一个带有图像文件扩展名的文件,并将其包含在内tsconfig.json。但是,当我尝试导入图像时,TS会对我大喊大叫Cannot find module。
.d.ts
tsconfig.json
Cannot find module
我的项目结构:
+ src + assets - image.jpg + components - Box.tsx - App.tsx - index.d.ts - index.html - index.tsx - tsconfig.json - tslint.json
我试图这样导入图像App.tsx。VS Code强调 '../assets/image.jpg'并说Cannot find module '../assets/image.jpg'。
App.tsx
'../assets/image.jpg'
Cannot find module '../assets/image.jpg'
import * as React from 'react'; import * as img from '../assets/image.jpg'; const Box = props => { // do things... } export default Box;
我在网上找到的讨论都指出需要.d.ts自己定义文件,因此我在index.d.ts这一行中创建了该文件。
index.d.ts
declare module '*.jpg';
然后添加"include": ["./src/index.d.ts"]到里面tsconfig.json,之后"compilerOptions" : {...}。
"include": ["./src/index.d.ts"]
"compilerOptions" : {...}
我错过了什么?如何解决TS抛出的错误?
如果按字面意义"include": ["./src/index.d.ts"]输入tsconfig.json并且没有"files"设置,则表示定义的项目tsconfig.json仅包含单个文件./src/index.d.ts。当您在VS Code中打开任何其他文件时,VS Code将使用不使用的单独的语言服务实例tsconfig.json。调整"include"设置以匹配项目中的.ts和.tsx文件,或者只是删除它并依靠默认行为,即将所有文件包含在包含的目录下tsconfig.json。
"files"
./src/index.d.ts
"include"
.ts
.tsx
TypeScript忽略了index.d.ts它,因为它假设它index.d.ts是由生成的,index.tsx并且index.tsx更有可能是最新的。将index.d.ts文件命名为其他名称,例如declaration.d.ts。
index.tsx
declaration.d.ts