How to load image files with webpack file-loader

后端 未结 6 1933
[愿得一人]
[愿得一人] 2020-11-27 09:13

I am using webpack to manage a reactjs project. I want to load images in javascript by webpack file-loader. Below is the

6条回答
  •  庸人自扰
    2020-11-27 09:59

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

    Prefixing with file!, passes the file into the file-loader again, and this time it doesn't have the name configuration.

    So your import should really just be:

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

    Update

    As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):

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

    Regarding problem #2

    After importing the png, the img variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext] (aka "file-loader? name=/public/icons/[name].[ext]"). Your output dir "dist" is unknown. You could solve this in two ways:

    1. Run all your code under the "dist" folder
    2. Add publicPath property to your output config, that points to your output directory (in your case ./dist).

    Example:

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

提交回复
热议问题