简体   繁体   English

(Webpack) 使用 url-loader 或 file-loader,我真的必须在我的 .js 中为我想要包含的每个静态图像包含一个 require() 吗?

[英](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.我仍在学习 webpack,我在让图像显示在我的生产版本中遇到了麻烦,直到我偶然发现了一些在 .js 文件顶部有一个require('path/to/image.png')的代码. 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.有像css-loaderurl-loader这样url-loader ,它们将url-loader解析为 base64 内联数据字符串,而不是提供静态资产。

You can see this great guide for how to implement with url-loader .你可以看到这个关于如何使用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.在构建 webpack 项目时,您可以使用CopyWebpackPluginsrc文件移动到 assets 文件夹。

Details in this answer: https://stackoverflow.com/a/33374807/492976此答案中的详细信息: 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.使用 React,npm 包babel-plugin-transform-react-jsx-img-import解析任何 img 元素,并且不需要显式导入或要求这些图像资源。

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

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

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

export default Image;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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