Vue Native中添加静态图片资源:如何实现静态识别?
Hey there! I get why this is confusing—Vue Native builds on React Native, so it inherits the same rule around static image assets: the require() calls for images need to be statically analyzable at build time. That’s why your initial <image :source="{require('./my-icon.png')}" /> isn’t working—Metro (the bundler used under the hood) can’t parse that dynamic require during compilation.
Here’s how to fix it, with common use cases:
Basic Static Image
For a single static image, define the require() in your component’s data (or directly in the template, though data is cleaner for maintainability):
<template> <image :source="staticIcon" /> </template> <script> export default { data() { return { // This require is statically picked up by the bundler staticIcon: require('./my-icon.png') } } } </script>
Conditional/State-Based Images
If you need to switch images based on a prop (like your active example), predefine all required images and toggle between them. Don’t try to dynamically construct the path in require()—Metro can’t resolve variable strings here.
Option 1: Use a watcher to update the image source
<template> <image :source="currentIcon" /> </template> <script> export default { props: ['active'], data() { return { currentIcon: require('./my-icon-inactive.png') } }, watch: { active(isActive) { this.currentIcon = isActive ? require('./my-icon-active.png') : require('./my-icon-inactive.png') } }, // Initialize the correct icon on mount mounted() { this.currentIcon = this.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png') } } </script>
Option 2: Use a map to store all image variants
This is great if you have more than two states to handle:
<template> <image :source="iconMap[active ? 'active' : 'inactive']" /> </template> <script> export default { props: ['active'], data() { return { iconMap: { active: require('./my-icon-active.png'), inactive: require('./my-icon-inactive.png'), disabled: require('./my-icon-disabled.png') // Add more as needed } } } } </script>
Why Your Original Approach Failed
When you write <image :source="{require('./my-icon.png')}" />, the require() is wrapped in an object that gets evaluated at runtime. Metro needs to see require() calls as top-level or directly assigned to variables during compilation to know which images to bundle. Dynamic wrappers break this static analysis.
Bonus: Dynamic Paths (If You Absolutely Need Them)
If you must use a variable to pick an image (e.g., my-icon-${status}.png), you’ll need to use native assets instead:
- For Android: Place images in
android/app/src/main/res/drawable/ - For iOS: Add images to your Xcode project’s Assets catalog
Then reference them using the URI syntax:
<image :source="{uri: `my-icon-${status}`}" />
Note that this treats the images as native resources, not project-level static assets, so your bundler won’t process them the same way.
内容的提问来源于stack exchange,提问作者Adam Beleko

