我用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目录,文件名为"df55075baa16f3827a575499950901e90.png".

Below is my project structure: enter image description here

另一个问题是,我用下面的代码导入了这个图像文件,但它没有显示在浏览器上.如果我使用的是url"public/icons/imageview\u item\u normal".在img标签上的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

一旦你在网页中配置了文件加载器.无论何时使用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]'
    }
}

因此你可以看到图像emits 到

dist/public/icons/imageview_item_normal.png

这是通缉犯的行为.

您获得哈希文件名的原因是,您正在添加一个额外的内联文件加载器.您正在将图像导入为:

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

前缀为file!,再次将文件传递到文件加载器,这次它没有名称配置.

所以你的导入应该是:

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

Update

正如@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
},

Reactjs相关问答推荐

如何在Pivot模式下自定义标题?

导致类型错误的调度不是函数";

ReferenceError:未在Redux组件中定义窗口

Npm运行构建`在Next.js 14中不起作用

将对象添加到集合中的数组时的no_id字段

如何将图像(在代码中称为自己)定位在蓝色圈内的点上?我正在使用material UI和Reaction

禁止直接访问Next.js中的页面,同时允许从应用程序内部访问

在新屏幕上显示照片时出现问题-react

有没有可能在next.js和ssr中使用tsps?

如何在next.js 13中仅在主页导航栏上隐藏组件?

React设置上下文并进行导航

Material UI @mui/material/Button vs @material-ui/core/Button,它什么时候改变的,旧版本的文档在哪里

React - 将一个充满空值的无限大小的数组存储在 ref 中是否可以,或者我应该重置数组吗?

如何让 useEffect 在 React.JS 中只运行一次?

为什么我的 Next.js (React) 组件只有在页面中时才有效?

在 React 中将路径与查询变量匹配

我正在try 使用 cypress 测试我的下拉列表,它 Select 值但不提交它们(手动工作)

当用户输入相同信息时如何禁用更新

未捕获的错误:操作必须是使用 redux/toolkit 的普通对象

仅在重新渲染后设置状态