Javascript 如何使用 webpack file-loader 加载图像文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37671342/
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
How to load image files with webpack file-loader
提问by Joey Yi Zhao
I am using webpackto manage a reactjsproject. I want to load images in javascript by webpack file-loader
. Below is the webpack.config.js:
我正在使用webpack来管理reactjs项目。我想通过 webpack 在 javascript 中加载图像file-loader
。下面是webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const PATHS = {
react: path.join(__dirname, 'node_modules/react/dist/react.min.js'),
app: path.join(__dirname, 'src'),
build: path.join(__dirname, './dist')
};
module.exports = {
entry: {
jsx: './app/index.jsx',
},
output: {
path: PATHS.build,
filename: 'app.bundle.js',
},
watch: true,
devtool: 'eval-source-map',
relativeUrls: true,
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.less'],
modulesDirectories: ['node_modules'],
alias: {
normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
},
],
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?presets=es2015',
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader?presets=es2015']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new NpmInstallPlugin({
save: true // --save
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
],
devServer: {
colors: true,
contentBase: __dirname,
historyApiFallback: true,
hot: true,
inline: true,
port: 9091,
progress: true,
stats: {
cached: false
}
}
}
I use this line to load image files and copy them to dist/public/icons directory and keep the same file name.
我使用这一行来加载图像文件并将它们复制到 dist/public/icons 目录并保持相同的文件名。
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"}
But I have two problems on using it. When I run webpack
command, the image file was copied to dist/public/icons/directory as expected. How, ver it was also copied to dist directory with this file name "df55075baa16f3827a57549950901e90.png".
但是我在使用它时有两个问题。当我运行webpack
命令时,图像文件已按预期复制到dist/public/icons/目录。如何,它也被复制到这个文件名为“df55075baa16f3827a57549950901e90.png”的dist目录中。
Below is my project structure:
Another problem is that I use below code to import this image file but it couldn't show on the browser. If I am using url 'public/icons/imageview_item_normal.png' on the img tag, it works fine. How to use the object imported from the image file?
另一个问题是我使用以下代码导入此图像文件,但无法在浏览器上显示。如果我在 img 标签上使用 url 'public/icons/imageview_item_normal.png',它工作正常。如何使用从图像文件中导入的对象?
import React, {Component} from 'react';
import {render} from 'react-dom';
import img from 'file!../../public/icons/imageview_item_normal.png'
export default class MainComponent extends Component {
render() {
return (
<div style={styles.container}>
download
<img src={img}/>
</div>
)
}
}
const styles = {
container: {
width: '100%',
height: '100%',
}
}
回答by omerts
Regarding problem #1
关于问题#1
Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched
一旦你在 webpack.config 中配置了文件加载器,每当你使用 import/require 时,它都会针对所有加载器测试路径,如果有匹配项,它会通过该加载器传递内容。在你的情况下,它匹配
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader?name=/public/icons/[name].[ext]"
}
and therefore you see the image emitted to
因此你会看到图像发射到
dist/public/icons/imageview_item_normal.png
which is the wanted behavior.
这是想要的行为。
The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:
您还获得哈希文件名的原因是因为您正在添加一个额外的内联文件加载器。您将图像导入为:
'file!../../public/icons/imageview_item_normal.png'.
Prefixing with file!
, passes the file into the file-loader again, and this time it doesn't have the name configuration.
以 为前缀file!
,再次将文件传递到文件加载器中,这次它没有名称配置。
So your import should really just be:
所以你的进口真的应该是:
import img from '../../public/icons/imageview_item_normal.png'
Update
更新
As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):
正如@cgatian 所指出的,如果您确实想使用内联文件加载器,而忽略 webpack 全局配置,则可以在导入前添加两个感叹号 (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
Regarding problem #2
关于问题#2
After importing the png, the img
variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext]
(aka "file-loader? name=/public/icons/[name].[ext]"
). Your output dir "dist" is unknown.
You could solve this in two ways:
导入 png 后,该img
变量仅保存文件加载器“知道”的路径,即public/icons/[name].[ext]
(又名"file-loader? name=/public/icons/[name].[ext]"
)。您的输出目录“dist”未知。您可以通过两种方式解决此问题:
- Run all your code under the "dist" folder
- Add
publicPath
property to your output config, that points to your output directory (in your case ./dist).
- 在“dist”文件夹下运行所有代码
- 将
publicPath
属性添加到您的输出配置中,该属性指向您的输出目录(在您的情况下为 ./dist)。
Example:
例子:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
回答by user3717160
I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.
我在将图像上传到我的 React JS 项目时遇到问题。我试图使用文件加载器来加载图像;我也在我的反应中使用了 Babel-loader。
I used the following settings in the webpack:
我在 webpack 中使用了以下设置:
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},
This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.
这有助于加载我的图像,但加载的图像有点损坏。然后经过一些研究,我开始知道 file-loader 在安装 babel-loader 时存在损坏图像的错误。
Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.
因此,为了解决这个问题,我尝试使用非常适合我的 URL-loader。
I updated my webpack with the following settings
我使用以下设置更新了我的 webpack
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},
I then used the following command to import the images
然后我使用以下命令导入图像
import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">
<img style={{ width: 300, height: 150 }} src={img} />
</div>
回答by Nalan Madheswaran
Install file loader first:
首先安装文件加载器:
$ npm install file-loader --save-dev
And add this rule in webpack.config.js
并在 webpack.config.js 中添加此规则
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
回答by Gaurav Paliwal
Alternatively you can write the same like
或者你可以写同样的
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
include: 'path of input image directory',
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'path of output image directory'
}
}
}
and then use simple import
然后使用简单的导入
import varName from 'relative path';
import varName from 'relative path';
and in jsx write like
<img src={varName} ..../>
并在 jsx 中这样写
<img src={varName} ..../>
....
are for other image attributes
....
用于其他图像属性
回答by Янов Алексей
webpack.config.js
webpack.config.js
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
}
anyfile.html
任何文件.html
<img src={image_name.jpg} />
回答by Felix
This is my working example of our simple Vue component.
这是我的简单 Vue 组件的工作示例。
<template functional>
<div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>