Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module '../assets/logo.png' at webpackEmptyContext (eval at ./src/component

I am trying to load an image url into a component using props but it seems like require cannot accept any variable. However, if I give require a plain text as parameter, it works

This one gives the error

Cannot find module '../assets/logo.png' at webpackEmptyContext (eval at ./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>

This one works:

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

Notice that I only changed the value inside require to a plain text

like image 805
TSR Avatar asked May 10 '19 20:05

TSR


1 Answers

Because webpack is a static build tool (it finds all the files needed at build time), a dynamic expression inside of that require statement isn't going to work because webpack has no idea what to resolve and where it exists.

That being said, a partial expression does provide webpack with enough information to load a file:

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

This would tell webpack:

Hey webpack, find me all the possible modules that can be resolved in this partial path, then at runtime, when this function is called, only serve up the JS Module that corresponds to the name passed in.

Here's a fancy diagram I give in my code splitting patterns talk

enter image description here

If you truly need to fetch an image dynamically, I'd recommend not using require() for this purpose then. Otherwise, ensure that the images you are going to serve up are in your local codebase.

like image 119
Sean Larkin Avatar answered Sep 24 '22 14:09

Sean Larkin