【问题标题】:Vite / Vue 3 : "require is not defined" when using image source as propsVite / Vue 3:使用图像源作为道具时“未定义要求”
【发布时间】:2021-12-10 06:24:21
【问题描述】:

我从 Vue CLI 切换到 Vite CLI,并从 Vue 3 的 Composition API 切换到 SFC Script setup API。

它以前对我有什么作用

当我使用官方Vue CLI时,我可以通过props传递路径的文件名来导入图像源:

<template>
  <img :src="require(`@/assets/${imagePath}`)"/>
<template/>

<script>
export default {
  props: {
    imagePath: { type: String },
  },
  setup() {
    // ...
  }
}
<script/>

然后这样称呼它:

<template>
  <Image imagePath="icon.png" />
</template>

我迁移到 Vite 后遇到的错误

但是自从我迁移到 Vite CLI 后,我遇到了一个错误“未捕获的 ReferenceError:require is not defined”。我的文件现在使用脚本设置语法,如下所示:

<script setup>
const props = defineProps({
  imagePath: { type: String },
})
</script>

<template>
  <img :src="require(`@/assets/${props.imagePath}`)"/>
</template>

我尝试了什么

我已经尝试使用相对路径直接从资产文件夹中导入文件,并且成功了。但是我不能用 import 语句指定 props 的路径。

<script setup>
// Works but do not use the props, so the component is not reusable
import logo from "./../assets/logo.png"
</script>

<template>
  <img :src="logo"/>
</template>
<script setup>
// Component is reusable but the import statement has illegal argument I guess
const props = defineProps({
  imagePath: { type: String },
})

import logo from `./../assets/${props.imagePath}`
</script>

<template>
  <img :src="logo"/>
</template>

我也尝试了模板中的 import 语句,但它甚至无法编译代码:

<script setup>
const props = defineProps({
  imagePath: { type: String },
})
</script>

<template>
  <img :src="import `./../assets/${props.iconPath}`" />
</template>

我错过了什么吗?也许有一个插件可以帮助我实现这一点?

【问题讨论】:

    标签: javascript vue.js vite


    【解决方案1】:

    在动态导入图像的imagePath 属性上使用watcher,并使用结果更新ref(绑定到&lt;img&gt;.src):

    <script setup>
    import { ref, watchEffect } from 'vue'
    
    const props = defineProps({
      imagePath: { type: String },
    })
    
    const logo = ref()
    watchEffect(async () => {
      logo.value = (await import(/* @vite-ignore */ `../assets/${props.imagePath}`)).default
    })
    </script>
    
    <template>
      <img :src="logo">
    </template>
    

    demo

    【讨论】:

    • 有趣的答案,不幸的是,它对我不起作用。我在控制台Unrestricted file system access to "C:/src/assets/logo.svg" For security concerns, accessing files outside of serving allow list will be restricted by default in the future version of Vite. Refer to https://vitejs.dev/config/#server-fs-allow for more details. 中收到此错误。这会导致浏览器出现此错误:Failed to load resource: the server responded with a status of 404。知道为什么我会收到此错误吗?我正在使用 Vite@2.6.4,@vitejs/plugin-vue@1.9.3
    • 你能分享一个复制链接吗?
    猜你喜欢
    • 2022-07-06
    • 2022-10-04
    • 2021-08-11
    • 2018-04-10
    • 1970-01-01
    • 2017-04-17
    • 2018-01-27
    • 2021-02-12
    相关资源
    最近更新 更多