如何使用webpack文件加载器加载图像文件

时间:2023-01-24 16:16:42

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:

我正在使用webpack来管理reactjs项目。我想通过webpack文件加载器在javascript中加载图像。下面是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 /目录。怎么样,它也被复制到dist目录,文件名为“df55075baa16f3827a57549950901e90.png”。

Below is my project structure: 如何使用webpack文件加载器加载图像文件

以下是我的项目结构:

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%',
  }
}

3 个解决方案

#1


139  

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

一旦在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

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”未知。您可以通过两种方式解决此问题:

  1. Run all your code under the "dist" folder
  2. 在“dist”文件夹下运行所有​​代码
  3. Add publicPath property to your output config, that points to your output directory (in your case ./dist).
  4. 将publicPath属性添加到输出配置,该输出配置指向输出目录(在您的情况下为./dist)。

Example:

例:

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},

#2


6  

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.

这有助于加载我的图像,但加载的图像有点破坏。然后经过一些研究后我才知道文件加载器在安装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>

#3


0  

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';

从'relative path'导入varName;

and in jsx write like <img src={varName} ..../>

并在jsx中写如如何使用webpack文件加载器加载图像文件

.... are for other image attributes

....用于其他图像属性

#1


139  

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

一旦在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

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”未知。您可以通过两种方式解决此问题:

  1. Run all your code under the "dist" folder
  2. 在“dist”文件夹下运行所有​​代码
  3. Add publicPath property to your output config, that points to your output directory (in your case ./dist).
  4. 将publicPath属性添加到输出配置,该输出配置指向输出目录(在您的情况下为./dist)。

Example:

例:

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},

#2


6  

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.

这有助于加载我的图像,但加载的图像有点破坏。然后经过一些研究后我才知道文件加载器在安装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>

#3


0  

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';

从'relative path'导入varName;

and in jsx write like <img src={varName} ..../>

并在jsx中写如如何使用webpack文件加载器加载图像文件

.... are for other image attributes

....用于其他图像属性