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

Joey Yi Zhao :

我正在使用webpack来管理reactjs项目。我想通过webpack在javascript中加载图像file-loader以下是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 /目录。但是,它也已使用此文件名“ df55075baa16f3827a57549950901e90.png”复制到dist目录。

下面是我的项目结构: 在此处输入图片说明

Another problem is that I used below code to import this image file but it is not showing 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?

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

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

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

加上前缀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](aka "file-loader? name=/public/icons/[name].[ext]")。您的输出目录“ dist”未知。您可以通过两种方式解决此问题:

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

例:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在 React & Django 中使用 webpack 的 URL 加载器时找不到图像文件

无法使用Webpack文件加载器加载图像

使用文件加载器加载Webpack车把图像

Webpack 4文件加载器适用于字体文件,但不适用于图像文件

Webpack-使用文件加载器要求图像

静态图像的 Webpack 文件加载器配置

如何将图像文件加载到ImageView?

使用 SDWebImage 从 Firebase 存储加载图像文件

强制React重新加载图像文件?

三.TextureLoader未加载图像文件

使用-> webpack使用相对路径从根目录加载图像-文件加载器-Angularjs

如何使用 Coil 将图像文件加载到 Jetpack Compose Image

如何告诉webpack仅对特定文件使用插件或加载器?

如何在webpack中使用文件加载器

如何使用Webpack 3,Typescript和文件加载器加载index.html文件?

用于.ejs模板中图像的Webpack文件/图像加载器

使用文件加载器从webpack的jQuery UI加载资产

为什么Webpack的Asset Manager无法加载我的图像文件?

webpack文件加载器冻结

Webpack文件加载器publicPath

从StreamingAssets文件夹读取/加载图像文件

Webpack文件加载器和CSS中的图像

用图像文件颤振加载图像资产

使用webpack中的文件加载器导入更少的文件

使用webpack文件加载器缩小/优化所需的文件

Webpack为使用文件加载器包含的图像生成错误的url

Webpack文件加载器不复制文件

webpack 文件加载器复制文件

显示加载的图像文件的 x,y 坐标