简体   繁体   中英

(Webpack) Using the url-loader or file-loader, do I really have to include a require() in my .js for every static image I want to include?

I'm still learning webpack, and I was having trouble getting images to show up in my production build until I stumbled upon some code which had a require('path/to/image.png') at the top of a .js file. So I tried it, and lo and behold it works.

This seems wonky to me. Do I really have to include one of these for every static image I need to serve? Is there a better way to do this? This is going to be messy if not.

There are loaders like css-loader and url-loader which resolve urls to base64 inlined data strings instead of serving up the static asset.

You can see this great guide for how to implement with url-loader . If you are having issues you need to make sure you are using the correct relative path.

'./path/to/image.png'

You can use the CopyWebpackPlugin to move src files to an assets folder when building the webpack project.

Details in this answer: https://stackoverflow.com/a/33374807/492976

Using React, the npm package babel-plugin-transform-react-jsx-img-import resolves any img elements and there is no need to explicit import or require those image resources.

import React from 'react';
const Image = () => {

   {* webpack configured to resolve
      the alias 'images' *}

   return (img src='images/foo.png'/>);
}

export default Image;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM