如何使用 webpack file-loader 加载图像文件 [英] How to load image files with webpack file-loader
问题描述
我正在使用 webpack 来管理 reactjs 项目.我想通过 webpack file-loader
在 javascript 中加载图像.下面是 webpack.config.js:
const webpack = require('webpack');const path = require('path');const NpmInstallPlugin = require('npm-install-webpack-plugin');常量路径 = {反应:path.join(__dirname, 'node_modules/react/dist/react.min.js'),应用程序:path.join(__dirname, 'src'),构建:path.join(__dirname, './dist')};模块.出口 = {入口: {jsx: './app/index.jsx',},输出: {路径:PATHS.build,文件名:'app.bundle.js',},看:真的,开发工具:'评估源地图',相对网址:真实,解决: {扩展名:['', '.js', '.jsx', '.css', '.less'],模块目录:['node_modules'],别名:{normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',}},模块: {预加载器: [{测试:/.js$/,加载器:源映射加载器";},],装载机: [{测试:/.html$/,loader: 'file?name=[name].[ext]',},{测试:/.jsx?$/,排除:/node_modules/,loader: 'babel-loader?presets=es2015',},{test:/.css$/, loader: 'style-loader!css-loader'},{测试:/.(jpe?g|png|gif|svg)$/i,加载器:file-loader?name=/public/icons/[name].[ext]"},{测试:/.js$/,排除:/node_modules/,装载机:['babel-loader?presets=es2015']}]},插件: [新的 webpack.optimize.UglifyJsPlugin({压缩:{警告:错误,},输出: {评论:假的,},}),新的 NpmInstallPlugin({保存:真//--save}),新的 webpack.DefinePlugin({process.env":{NODE_ENV: JSON.stringify(生产")}}),],开发服务器:{颜色:真实,contentBase: __dirname,historyApiFallback: 真,热:真的,内联:真实,端口:9091,进度:真实,统计:{缓存:假}}}
我用这一行来加载图像文件并将它们复制到 dist/public/icons 目录并保持相同的文件名.
{test:/.(jpe?g|png|gif|svg)$/i, loader: file-loader?name=/public/icons/[name].[ext]";}
但是我在使用时遇到了两个问题.当我运行 webpack
命令时,图像文件已按预期复制到 dist/public/icons/ 目录.然而,它也被复制到 dist 目录,文件名为df55075baa16f3827a57549950901e90.png".
以下是我的项目结构:
另一个问题是我使用下面的代码来导入这个图像文件,但它没有显示在浏览器上.如果我在 img 标签上使用 url 'public/icons/imageview_item_normal.png',它工作正常.如何使用从图像文件中导入的对象?
import React, {Component} from 'react';从 'react-dom' 导入 {render};从文件!../../public/icons/imageview_item_normal.png"导入 img导出默认类 MainComponent extends Component {使成为() {返回 (<div style={styles.container}>下载<img src={img}/>
)}}常量样式 = {容器: {宽度: '100%',高度:'100%',}}
关于问题 #1
一旦你在 webpack.config 中配置了文件加载器,每当你使用 import/require 时,它都会针对所有加载器测试路径,如果有匹配,它会通过该加载器传递内容.在你的情况下,它匹配
<代码>{测试:/.(jpe?g|png|gif|svg)$/i,loader: file-loader?name=/public/icons/[name].[ext]";}//对于较新版本的 Webpack,它应该是{测试:/.(jpe?g|png|gif|svg)$/i,加载器:'文件加载器',选项: {name: '/public/icons/[name].[ext]'}}
因此你看到图像发射到
dist/public/icons/imageview_item_normal.png
这是想要的行为.
您还获得哈希文件名的原因是因为您添加了一个额外的内联文件加载器.您正在将图像导入为:
'file!../../public/icons/imageview_item_normal.png'.
以file!
为前缀,再次将文件传入file-loader,这次没有name配置.
所以你的导入应该是:
从'../../public/icons/imageview_item_normal.png'导入img
更新
正如@cgatian 所指出的,如果你真的想使用内联文件加载器,而忽略 webpack 全局配置,你可以在导入前加上两个感叹号 (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
关于问题#2
导入 png 后,img
变量只保存文件加载器知道"的路径,即 public/icons/[name].[ext]
代码>(又名 file-loader? name=/public/icons/[name].[ext]"
).你的输出目录dist"未知.您可以通过两种方式解决此问题:
- 在dist"下运行所有代码文件夹
- 将
publicPath
属性添加到您的输出配置中,该属性指向您的输出目录(在您的情况下为 ./dist).
示例:
输出:{路径:PATHS.build,文件名:'app.bundle.js',公共路径:PATHS.build},
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 used 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]"}
But I have two problems when using it. When I run webpack
command, the image file was copied to dist/public/icons/ directory as expected. However it was also copied to dist directory with this file name "df55075baa16f3827a57549950901e90.png".
Below is my project structure:
Another problem is that I used below code to import this image file but it is not showing 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%',
}
}
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]"
}
// For newer versions of Webpack it should be
{
test: /.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
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.
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 (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
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:
- 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).
Example:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
这篇关于如何使用 webpack file-loader 加载图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!