We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
之前写TS没遇到过导入图片的需求,刚好今天写代码的时候需要导入图片,算是小踩了一个坑,予以记录一下;
TS
正常导入图片我们这样做,日常react写法:
import React from 'react' import img from './xxx.png' export default class MyComponent extends React.Component { render() { return ( <div> <img src={img} alt="img" /> </div> ) } }
TypeScript的写法:
import * as React from 'react' import img from './xxx.png' class MyComponent extends React.Component<any, any> { public render(): JSX.Element { return ( <div> <img src={img} alt="img" /> </div> ) } } export default MyComponent
上面这种写法看似没毛病,实际渲染src则是空的,在网页上以破图呈现。检查了好几次代码,没发现问题出在哪?然后我就在开始试着打log调试我的这几行代码,依次在:
import * as React from 'react' import img from './xxx.png' console.log('img', img) class MyComponent extends React.Component<any, any> { public render(): JSX.Element { console.log('render img', img) return ( <div> <img src={img} alt="img" /> </div> ) } } export default MyComponent
两次log的地方都返回undefined ,说明图片根本没有导入进来。试着找到问题所在,发现TypeScript不使用webpack配置,所以遇到import img from 'xxx.png';这种情况他不知道怎么去处理它。
undefined
import img from 'xxx.png';
我尝试着用import * as name语法导入所有导出,解决这个问题:
import * as name
import * as React from 'react' import * as img from './xxx.png' class MyComponent extends React.Component<any, any> { public render(): JSX.Element { return ( <div> <img src={img} alt="img" /> </div> ) } } export default MyComponent
这样写就似乎是找到图片了,但是我总觉得问题还没有彻底解决。因为VSCode 报错了,[ts] 找不到模块。我在tsconfig.js 里配置了'allowSyntheticDefaultImports': true, 允许从没有设置默认导出的模块中默认导入, 正常的情况应该不用再写成import * as name ...的形式才对。虽然用另一种办法解决了,但并没有完美解决,等这周空闲下来再来好好研究。
[ts] 找不到模块
'allowSyntheticDefaultImports': true
import * as name ...
参考:webpack not able to import images( using express and angular2 in typescript) - Stack Overflow
The text was updated successfully, but these errors were encountered:
No branches or pull requests
之前写
TS
没遇到过导入图片的需求,刚好今天写代码的时候需要导入图片,算是小踩了一个坑,予以记录一下;正常导入图片我们这样做,日常react写法:
TypeScript的写法:
上面这种写法看似没毛病,实际渲染src则是空的,在网页上以破图呈现。检查了好几次代码,没发现问题出在哪?然后我就在开始试着打log调试我的这几行代码,依次在:
两次log的地方都返回
undefined
,说明图片根本没有导入进来。试着找到问题所在,发现TypeScript不使用webpack配置,所以遇到import img from 'xxx.png';
这种情况他不知道怎么去处理它。我尝试着用
import * as name
语法导入所有导出,解决这个问题:这样写就似乎是找到图片了,但是我总觉得问题还没有彻底解决。因为VSCode 报错了,
[ts] 找不到模块
。我在tsconfig.js 里配置了'allowSyntheticDefaultImports': true
, 允许从没有设置默认导出的模块中默认导入, 正常的情况应该不用再写成import * as name ...
的形式才对。虽然用另一种办法解决了,但并没有完美解决,等这周空闲下来再来好好研究。参考:webpack not able to import images( using express and angular2 in typescript) - Stack Overflow
The text was updated successfully, but these errors were encountered: