我正在使用 React 应用程序并使用 Webpack &amp;的打字稿即可。我想在其中一个<img/>
标签中使用图片。但是,我没有找到正确的方法来访问图像文件。
webpack.config.js :
...
module: {
rules: [
...
{
test: /\.(png|jpe?g|svg)$/,
loader: 'file-loader',
options: {
name: 'assets/[name].[ext]',
}
}
]
app.tsx :
...
render() {
return <img src='/assets/logo-large.png' alt="logo"/>
}
运行应用时,找不到assets/logo-large.png
资源。
答案 0 :(得分:16)
或者,在custom_typings文件夹中(如果有),您可以添加新的import-png.d.ts
文件:
declare module "*.png" {
const value: any;
export default value;
}
因此您可以使用以下方式导入图像:
import myImg from 'img/myImg.png';
或者,正如@ mario-petrovic报道的那样,您有时需要使用不同的导出选项,如下所示(export = syntax)。有关两种方法之间的差异,请参阅here:
declare module "*.png" {
const value: any;
export = value;
}
在这种情况下,您可能需要将图像导入为:
import * as myImg from 'img/myImg.png';
答案 1 :(得分:12)
您需要require
图像然后使用该变量作为源,如下所示:
// At the top of the file, with all other imports/requires
const imageSrc = require('/assets/logo-large.png')
...
render() {
return <img src={String(imageSrc)} alt="logo"/>
}
答案 2 :(得分:12)
在花了一些时间找出解决方案之后,这就是我所做的......
确保您已安装 file-loader
作为开发依赖项
npm install -D file-loader
,如果你使用纱线 yarn add -D file-loader
在Webpack规则webpack.config.js
中添加文件扩展名对应的loader,像这样
module: {
rules: [
...,
{
test: /\.(png|jpe?g|gif|jp2|webp)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
},
],
},
在您的 index.d.ts
文件旁边创建一个 tsconfig.json
文件,实际上您可以随意命名它,但您必须按照步骤 4 进行操作。
由于 Webpack 现在将处理多个图像扩展,因此您可以添加 file-loader 支持的其他图像格式
declare module '*.png';
declare module '*.jpg';
转到您的 tsconfig.json
文件并将 index.d.ts
添加到包含数组中,如下所示:
{
"compilerOptions": {
...,
"jsx": "react",
"esModuleInterop": true,
"target": "ES2020",
"moduleResolution": "node"
},
"exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
"include": ["src", "index.d.ts"] /// <-- Like this!!
}
请注意,如果您尚未定义 include
数组,则默认情况下打字稿将添加根文件夹中的所有文件,如果您只定义一个文件而不是包含所有代码的文件它不会编译。我认为将所有代码放在 src 文件夹中是一个好习惯。
瞧!!
答案 3 :(得分:1)
copy-webpack-plugin
也可能会解决您的问题,当您有很多图像时,只需从一个中央dist
文件夹中提供所有图像即可。
npm install --save-dev copy-webpack-plugin
plugins: [
...
...
new CopyWebpackPlugin([
{from:'src/images',to:'images'}
]),
...
]
否,您不能简单地指向图像标签的相对路径:
<img src='images/your-image.png' />
答案 4 :(得分:0)
实际上,您不需要 webpack 来使用 webp 图像。此解决方案也适用于基于 TypeScript 和 JavaScript 的 React 应用程序。如果您尝试将 webp 图像导入为 ReactComponent,TypeScript 会出现错误。所以你不应该把它作为一个组件导入,而应该只使用图像的来源。检查这个例子:
import img from "./images/image.webp";
现在您可以像这样在 标签中使用此 src。
<img src={img} />