在webpackEmptyContext上找不到模块'../assets/logo.png'(eval在./src/component

时间:2019-05-10 20:49:41

标签: vue.js webpack vue-component

我正在尝试使用props将图像url加载到组件中,但似乎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>

此作品有效:

<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>

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

2 个答案:

答案 0 :(得分:0)

因为webpack是一个静态构建工具(它会在构建时查找所有需要的文件),所以该require语句中的动态表达式无法正常工作,因为webpack不知道该解决什么以及在哪里它存在。

也就是说, partial 表达式确实为webpack提供了足够的信息来加载文件:

imglink: function() {
  const {someImageName} = this; 
  return require("../assets/${someImageName}");
}

这将告诉webpack:

  

嘿,在Webpack中,找到我可以在此部分路径中解析的所有可能模块,然后在运行时调用此函数时,仅提供与传入名称相对应的JS模块。

这是我在code splitting patterns talk中给出的漂亮图表

enter image description here

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

答案 1 :(得分:0)

我遇到了同样的问题,发现 Webpack 是一个静态构建工具,所以我们通常不能使用动态需要。

但关于解决方案:

  1. 解决方案 #1 使用 partial expressions(描述为 here

但是使用 regx 捆绑了所有匹配的模块,这不是那么动态,也可能不是您想要的。

  1. 解决方案 #2 适用于仅定位 node(而非浏览器)的情况:(source)
const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
const foo = requireFunc(moduleName);

这样 webpack 会将普通节点 require 放在包上。

  1. 解决方案 #3 也仅适用于 node 目标。您可以创建一个 native-require.js 文件,如下所示 (source):
module.exports = require

并告诉 webpack 不要解析它,把它放在 webpack.config.js 上:

module.exports = {
  "target": "node",
  "module": {"noParse": /native-require.js/}
}

然后您可以像这样导入本机需要:const r = require('./native-require') 并使用它来动态导入您的模块。

我测试了 #2 和 #3 并且都有效。