在 webpackEmptyContext 中找不到模块“../assets/logo.png”(评估在 ./src/component

TSR*_*TSR 5 webpack vue.js vue-component

我正在尝试使用 props 将图像 url 加载到组件中,但似乎 require 不能接受任何变量。但是,如果我给 require 一个纯文本作为参数,它就可以工作

这个给出了错误

在 webpackEmptyContext 中找不到模块“../assets/logo.png”(评估在 ./src/component

<template>
    <div>

        {{imagelink}}
        <div style="width: 150px; height: 150px; background-color: red">
            <img :src="imglink" alt="" height="150px" width="150px">
        </div>
    </div>
</template>

<script>
    export default {
        name: "ImageTest",
        props:{
            imagelink: String,
        },
        computed: {
            imglink: function () {
                // this.imagelink
                const modulepatha = '../assets/logo.png'
                return  require(modulepatha)
            }
        }
    }</script>

<style scoped>
</style>
Run Code Online (Sandbox Code Playgroud)

这个有效:

<template>
    <div>

        {{imagelink}}
        <div style="width: 150px; height: 150px; background-color: red">
            <img :src="imglink" alt="" height="150px" width="150px">
        </div>
    </div>
</template>

<script>
    export default {
        name: "ImageTest",
        props:{
            imagelink: String,
        },
        computed: {
            imglink: function () {
                // this.imagelink
                const modulepatha = '../assets/logo.png'
                return  require('../assets/logo.png') //changed this
            }
        }
    }</script>

<style scoped>
</style>
Run Code Online (Sandbox Code Playgroud)

请注意,我只将 require 中的值更改为纯文本

Sea*_*kin 13

因为 webpack 是一个静态构建工具(它会在构建时找到所有需要的文件),该require语句中的动态表达式将不起作用,因为 webpack 不知道要解析什么以及它存在于何处。

话虽如此,部分表达式确实为 webpack 提供了足够的信息来加载文件:

imglink: function() {
  const {someImageName} = this; 
  return require("../assets/${someImageName}");
}
Run Code Online (Sandbox Code Playgroud)

这会告诉 webpack:

嘿,webpack,把这个部分路径中所有可能解析的模块都找给我,然后在运行时,调用这个函数的时候,只提供传入的名字对应的JS Module。

这是我在我的代码拆分模式演讲中给出的精美图表

在此处输入图片说明

如果您确实需要动态获取图像,我建议您不要require()用于此目的。否则,请确保您要提供的图像在您的本地代码库中。

  • 嘿肖恩。快问。那你会推荐什么? (3认同)