如何使用 webpack 文件加载程序加载图像文件

2022-08-30 02:11:25

我正在使用webpack来管理reactjs项目。我想通过webpack加载javascript中的图像。下面是 webpack.config.jsfile-loader

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]"}

但是我在使用它时有两个问题。当我运行命令时,图像文件被复制到dist/public/icons/目录,如预期的那样。但是,它也被复制到此文件名为“df55075baa16f3827a57549950901e90.png”的dist目录中。webpack

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

另一个问题是我使用下面的代码来导入此图像文件,但它没有显示在浏览器上。如果我在img标签上使用网址“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

关于问题#1

在 webpack.config 中配置文件加载程序后,每当您使用 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 后,该变量仅保存文件加载程序“知道”的路径,即 (aka )。您的输出目录“dist”未知。您可以通过两种方式解决此问题:imgpublic/icons/[name].[ext]"file-loader? name=/public/icons/[name].[ext]"

  1. 在“dist”文件夹下运行所有代码
  2. 将属性添加到输出配置,该属性指向输出目录(在本例中为 ./dist)。publicPath

例:

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

答案 2

我在将图像上传到我的 React JS 项目时遇到问题。我试图使用文件加载器来加载图像;我也在我的反应中使用了Babel加载器。

我在网络包中使用了以下设置:

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

这有助于加载我的图像,但加载的图像有点损坏。然后经过一些研究,我开始知道文件加载器在安装babel加载器时有一个损坏图像的错误。

因此,为了解决这个问题,我试图使用适合我的URL加载器。

我使用以下设置更新了我的网络包

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