如何使用webpack的file-loader加载图像文件

178

我正在使用 webpack 来管理一个 reactjs 项目。我想通过 webpack 的 file-loader 在 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
        }
    }
}
我使用这行代码加载图像文件并将它们复制到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"。

下面是我的项目结构: enter image description here

另一个问题是,我使用以下代码导入此图像文件,但它在浏览器上不显示。如果我在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%',
  }
}

1
你尝试过移除url-loader吗? - Jaime
我从webpack配置文件中删除了url-loader,并删除了dist目录,然后重新运行了webpack命令,但问题仍然存在。文件已生成。 - Joey Yi Zhao
7个回答

244

关于问题#1

一旦你在webpack.config中配置了file-loader,无论何时使用import/require导入文件时,它都会将路径与所有加载器进行匹配,并在有匹配的情况下通过该加载器传递内容。在你的情况下,它匹配了

{
    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]'
    }
}

因此,您可以看到发出的图像

dist/public/icons/imageview_item_normal.png

这是所期望的行为。

你也会得到哈希文件名的原因是因为你添加了额外的内联文件加载器。你将图片导入为:

'file!../../public/icons/imageview_item_normal.png'.

在文件名前加上file!,将文件再次传递给文件加载器,这一次它没有名称配置。

因此,你的导入实际上应该只是:

import img from '../../public/icons/imageview_item_normal.png'

更新

正如@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”是未知的。

你可以通过以下两种方法解决这个问题:

  1. 在“dist”文件夹下运行所有代码
  2. publicPath属性添加到你的输出配置中,指向你的输出目录(在你的情况下是./dist)。

例如:

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

181
这是整个互联网上唯一一个文件,它说“publicPath”将改变文件加载器使用的URL。 - Tyler Jones
如果我像这样使用 &name=/fonts/[name].[ext],它会忽略 publicPath,但如果我像这样使用 &name=fonts/[name].[ext],它会尝试在相对路径内搜索它。例如,如果一个包使用此字体资源并位于 vender 文件夹内,它将在 [publicPath]/vendor/file 中搜索文件,但该文件保存在 vendor 文件夹的上一级。(顺便说一下,我正在使用 url-loader,但将其限制设置得很低,以便它回退到 file-loader)。 - Sagiv b.g
1
只是为了补充答案。(请编辑,因为我认为这很有用)如果您发现自己处于想要在 require 语句上绕过 webpack 配置的情况下,您可以在导入之前添加两个额外的感叹号 require('!!file-loader!wenis.png'); - cgatian
2
自上述声明以来,文档已经得到了极大的改进 :) - 请参见:https://github.com/webpack-contrib/file-loader#options,并在以下链接中获取有关publicPath的更多信息:https://github.com/webpack-contrib/file-loader#publicpath - Pavelloz
Error: Compiling RuleSet failed: Query arguments on 'loader' has been removed in favor of the 'options' property (at ruleSet[1].rules[1].loader: file-loader?name=/img/[name].[ext]) - João Pimentel Ferreira
@JoãoPimentelFerreira 更新了webpack的新版本配置,感谢。 - omerts

24

我在我的React JS项目中上传图片时遇到了问题。我尝试使用file-loader来加载图片;我还在我的react中使用了Babel-loader。

我在webpack中使用了以下设置:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

这帮助我加载了图片,但是加载的图片有点损坏。后来经过一些研究,我知道file-loader在安装babel-loader时会造成图像损坏的问题。

因此,为了解决这个问题,我尝试使用URL-loader,这对我来说完美地解决了问题。

我更新了我的webpack配置如下:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

我接着使用以下命令来导入图片

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />
</div>

1
谢谢!我尝试了很多方法并阅读了您的评论,使用了url-loader。许多帖子都说要使用file-loader,但在使用webpack和react时一直给我404错误。我在webpack配置中使用了{test: /.(jpe?g|png|gif|svg)$/i, loader: "url-loader"}。 - sadlyfe

12

首先安装文件加载器:

$ npm install file-loader --save-dev

在webpack.config.js中添加这个规则

           {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {}
                }]
            }

9

另外,你也可以写成这样

{
    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'
        }
    }
}

然后使用简单的导入

import varName from '相对路径';

在JSX中像这样编写:<img src={varName} ..../>

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


1
这个结尾部分对于由jsx插入的图像非常重要,感谢@gaurav-paliwal。使用import imgPath帮助我解决了这个问题,并且图像被复制到了dist/build文件夹中。 - Ebrahim
1
那个 outputPath 键帮助我找到了放置带有子文件夹的文件的位置。这里的其他答案都没有起作用。非常感谢。 - Thielicious

6

使用webpack5,您可以使用资产模块代替文件加载器。

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

如需更多信息,请访问文档


1

webpack.config.js

{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name].[ext]',
    },
}

anyfile.html

<img src={image_name.jpg} />

0

这是我们简单的Vue组件的工作示例。

<template functional>
    <div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接