Webpack 和 Typescript 图像导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43638454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Webpack & Typescript image import
提问by Cosmin SD
I'm working on a Reactapplication and using Webpack& Typescript. I would like to use an image in one of the <img/>
tags. However, I did not find the proper way to have access to the image files.
我正在开发一个React应用程序并使用Webpack& Typescript。我想在其中一个<img/>
标签中使用图像。但是,我没有找到访问图像文件的正确方法。
webpack.config.js:
webpack.config.js:
...
module: {
rules: [
...
{
test: /\.(png|jpe?g|svg)$/,
loader: 'file-loader',
options: {
name: 'assets/[name].[ext]',
}
}
]
app.tsx:
应用程序.tsx:
...
render() {
return <img src='/assets/logo-large.png' alt="logo"/>
}
When running the app, the assets/logo-large.png
resource is not found.
运行应用程序时,assets/logo-large.png
找不到资源。
采纳答案by Erik Vullings
Alternatively, in your custom_typings folder (if you have that), you can add a new import-png.d.ts
file:
或者,在您的 custom_typings 文件夹(如果有)中,您可以添加一个新import-png.d.ts
文件:
declare module "*.png" {
const value: any;
export default value;
}
So you can import an image using:
因此,您可以使用以下方法导入图像:
import myImg from 'img/myImg.png';
Alternatively, as reported by @mario-petrovic, you sometimes need to use a different export option as below (export = syntax). See herefor the differences between the two approaches:
或者,正如@mario-petrovic 所报告的,您有时需要使用不同的导出选项,如下所示(export = 语法)。请参阅此处了解两种方法之间的差异:
declare module "*.png" {
const value: any;
export = value;
}
In which case you probably need to import the image as:
在这种情况下,您可能需要将图像导入为:
import * as myImg from 'img/myImg.png';
回答by ahstro
You need to require
the image and then use that variable as the source, like so:
您需要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"/>
}
回答by IAMTHEBEST
The copy-webpack-plugin
might solve your problem as well, when you have a lot of images you can just serve them all from one central dist
folder.
这copy-webpack-plugin
也可能会解决您的问题,当您有很多图像时,您可以从一个中央dist
文件夹中提供所有图像。
npm install --save-dev copy-webpack-plugin
npm install --save-dev copy-webpack-plugin
plugins: [
...
...
new CopyWebpackPlugin([
{from:'src/images',to:'images'}
]),
...
]
No you can simply at the relative path to your image tag:
不,您可以简单地在图像标签的相对路径上:
<img src='images/your-image.png' />
<img src='images/your-image.png' />
来源:https: //medium.com/a-beginners-guide-for-webpack-2/copy-all-images-files-to-a-folder-using-copy-webpack-plugin-7c8cf2de7676