如何使用webpack文件加载器加载图像文件 [英] How to load image files with webpack file-loader
问题描述
我正在使用 webpack 来管理 reactjs 项目。我想通过webpack file-loader
在javascript中加载图像。以下是 webpack.config.js :
I am using webpack to manage a reactjs project. I want to load images in javascript by webpack file-loader
. Below is the 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使用此行加载图像文件并将它们复制到dist / public / icons目录并保持相同的文件名。
I use this line to load image files and copy them to dist/public/icons directory and keep the same file name.
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"}
但是我在使用它时有两个问题。当我运行 webpack
命令时,图像文件按预期复制到 dist / public / icons / 目录。如何,它也被复制到dist目录,文件名为df55075baa16f3827a57549950901e90.png。
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".
以下是我的项目结构:
Below is my project structure:
另一个问题是我使用下面的代码导入此图像文件,但它无法在浏览器上显示。如果我在img标签上使用url'public / icons / imageview_item_normal.png',它可以正常工作。如何使用从图像文件导入的对象?
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?
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%',
}
}
推荐答案
关于问题#1
一旦你在webpack.config中配置了文件加载器,每当你使用import / require时它测试针对所有加载器的路径,如果有匹配,它会通过该加载器传递内容。在你的情况下,它匹配
Regarding problem #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
{
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
这是想要的行为。
你也得到哈希文件名的原因是因为你要添加一个额外的内联文件加载器。您将图像导入为:
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.
所以你的导入应该只是:
So your import should really just be:
import img from '../../public/icons/imageview_item_normal.png'
更新
如@cgatian所述,如果你真的想使用内联文件加载器,忽略webpack全局配置,你可以在导入前加上两个感叹号(!!):
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 (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
关于问题#2
导入后png, img
变量只保存文件加载器知道的路径,即 public / icons / [name]。[ext ]
(又名file-loader?name = / public / icons / [name]。[ext]
)。您的输出目录dist未知。
您可以通过两种方式解决这个问题:
Regarding problem #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:
- 在dist文件夹下运行所有代码
- 将
publicPath
属性添加到输出配置中,该输出配置指向输出目录(在您的情况下为./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).
示例:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
这篇关于如何使用webpack文件加载器加载图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!