Vue项目:使用require解析图片的存放位置及生效复制路径问询
Answers to Your Vue Image Path Questions
1. Where to place images when using require() in Vue projects?
When using require() to resolve image paths in Vue, you have two main recommended locations depending on your needs:
src/assetsdirectory: This is the conventional home for project-specific static assets. You can reference images here using the@alias (which maps to thesrcfolder) likerequire('@/assets/your-image.jpg'). Webpack will process these images—compress them, hash filenames for cache busting, etc.—during the build, which is ideal for production.publicdirectory: If you put images here, you can reference them withrequire('/your-image.png')since thepublicfolder acts as your app's root static asset folder. Note that images here won't be processed by Webpack; they'll retain their original names and paths, which is useful for static assets you don't want modified.- Bonus: You can also place images directly in your component folders and use relative paths like
require('./your-image.svg'), but this can get disorganized as your project scales, so sticking tosrc/assetsorpublicis better for maintainability.
2. Where to copy Vue Bootstrap images to avoid modifying transformToRequire?
Since you want to skip tweaking the transformToRequire config, the simplest, config-free approach is to use your project's public directory:
- Create a
publicfolder at the root of yourmyProjectif it doesn't already exist. - Copy the Vue Bootstrap images into a subfolder inside
publicthat matches the path used in the Vue Bootstrap code. For example, if the code uses<img src="/icons/arrow-right.png">, createpublic/iconsand placearrow-right.pngthere. - This works because assets in
publicare served directly from the root URL, so the browser can load them without needing Webpack to resolve the path viarequire()or special configuration.
If you'd rather keep images in src/assets, you'd have to update each Vue Bootstrap image reference to use require() bindings (like <img :src="require('@/assets/icons/arrow-right.png')">), but that requires editing every image link—so the public folder is definitely the faster option here.
内容的提问来源于stack exchange,提问作者Fractal
相关产品推荐
相关产品推荐

