如何用webpack文件加载器加载图片文件

我正在使用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" 。

下面是我的项目结构。 ![在此输入图片描述][1]

另一个问题是,我使用下面的代码来导入这个图片文件,但它在浏览器上无法显示。如果我在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

一旦你在webpack.config中配置了文件加载器,每当你使用import/require时,它就会针对所有加载器测试路径,如果有匹配的,它就会通过该加载器传递内容。在你的案例中,它匹配了

{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: "file-loader?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]")。你的输出dir "dist"是未知的。 你可以用两种方法解决这个问题。

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

例子。

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},
评论(6)

我在向我的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有一个bug,就是在安装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">


</div>
评论(0)

或者你也可以这样写

{
    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 'relative path';

并在jsx中这样写 ``。

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

评论(1)