admin管理员组文章数量:1134246
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%',
}
}
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%',
}
}
Share
Improve this question
edited Jun 30, 2020 at 13:48
user5486312
asked Jun 7, 2016 at 5:40
Joey Yi ZhaoJoey Yi Zhao
42.3k86 gold badges344 silver badges648 bronze badges
2
- 1 Have you tried removing the url-loader? – Jaime Commented Jun 7, 2016 at 5:47
- 1 I removed the url-loader from webpack config file and remove the dist directory and rerun webpack command, the problem is still there. The file was generated. – Joey Yi Zhao Commented Jun 7, 2016 at 6:19
7 Answers
Reset to default 245Regarding 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
},
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.
I used the following settings in the 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.
Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.
I updated my webpack with the following settings
{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>
Install file loader first:
$ npm install file-loader --save-dev
And add this rule in webpack.config.js
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
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';
and in jsx write like
<img src={varName} ..../>
....
are for other image attributes
With the webpack5 you can use Asset Modules instead of file loader.
Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders.Asset Modules type replaces by adding asset/resource emits a separate file and exports the URL. Previously achievable by using file-loader.
module: {
rules: [
{
test: /\.png/,
type: 'asset/resource'
}
]
},
For more information please visit the documentation.
webpack.config.js
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
}
anyfile.html
<img src={image_name.jpg} />
This is my working example of our simple Vue component.
<template functional>
<div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>
本文标签: javascriptHow to load image files with webpack fileloaderStack Overflow
版权声明:本文标题:javascript - How to load image files with webpack file-loader - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736780705a1952578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论