Utilizing Visuals from a Vue Component Collection

As I attempt to publish a Vue library to npmjs, I encounter an issue with the images within it.

After publishing the app to NPM and importing it into my main app, everything appears to be working correctly. However, the paths to the images in the library are incorrect, and I am unable to fix them (I notice that the images are located in the node_modules folder of my library. Shouldn't my main vue app extract the images from the library when I run npm run serve?)

To better understand this problem, I have created a simplified demo.

Within my Library, I have developed a basic component:

<div class="hello">
  <h1>{{ msg }}</h1>
  <img alt="Vue logo" src="@/assets/xlogo.png" />
  <img alt="Vue logo" :src="require('../assets/xlogo.png')" />
  <p>This is a paragraph.</p>
</div>

I then build the library using the following node command (the command is specified in the package.json, and I execute it via npm run build:lib):

vue-cli-service build --target lib --name tmp ./src/components/index.vue

Subsequently, I import the library into my main vue app:

import HelloWorld from '../../tmp/dist/tmp.umd.js' 

<template>
  <HelloWorld msg="Welcome to Your Vue.js App.."/>
</template>

To illustrate this issue, I have set up a GitHub repository. How can I resolve this so that the images are included in the library? Any guidance would be greatly appreciated, as I have dedicated hours trying to solve this on my own already :(

Answer №1

Ugh... it took much longer than I expected to solve this issue.

I had to set up webpack to convert the images into base64 format. The downside is that the app package becomes larger because the images are now included in the code, but since I only have a few images, it's not a big deal for me.

Here's how to fix it:

1: Install Url Loader

npm install --save-dev url-loader

2: Create a vue.config.js file and configure it to use the url loader for images

module.exports = {
      chainWebpack: (config) => {
        config.module
          .rule("images")
          .test(/\.(png|jpg|svg)$/i)
          .use("url-loader")
          .loader("url-loader")
          .tap(options => Object.assign(options, { limit: 10240 }));
      },
    }

That's all. Note that using require directly in the vue template did not work.

<template>
  <div class="hello">
    <div><img src="~@/assets/logo.png" /></div> <!-- Working -->
    <div><img src="@/assets/logo.png" /></div> <!-- Working -->
    <div><img :src="imgPath" /></div> <!-- Working -->
    <div><img :src="require('../assets/logo.png')" /></div> <!-- Not Working -->
    <div><img :src="require('../assets/logo.png')" /></div> <!-- Not Working -->
  </div>
</template>

<script>
import imgPath from "@/assets/logo.png";

export default {
  setup() {
    return {
      imgPath,
    };
  },
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different ways to set the depth parameter in npm

The NPM manual mentions specifying depth as an integer parameter. For more information, visit the NPM documentation. I attempted various methods but none seem to be effective. $ npm --depth=1 list $ npm --depth 1 list $ npm depth 1 list $ npm depth:1 li ...

Utilizing adapter headers in contexts other than ActiveModelAdapter

I have successfully implemented my authorization system with Ember Data. All my ember-data calls are secure and signed correctly using adapter.ajax() instead of $.ajax. However, I am facing a situation where I need to utilize a third-party upload library t ...

npm build is encountering an issue where the Class it is extending has a value of undefined, which is neither

Despite reviewing similar questions and answers, my knowledge of npm is limited, and I am struggling to apply those solutions to my current issue. While trying to build a project, I encountered the following error: ERROR TypeError: Class extends valu ...

Is jQuery failing to correctly validate the RadioButtonList?

Using jQuery, I am attempting to validate a RadioButtonList to make sure that the user has selected one of the values. If none of the radio buttons are checked, an alert message should appear. However, even after selecting a radio button, the alert continu ...

Error message on Android Web Console: ReferenceError - Worker object is not defined

As someone who is new to javascript, I have been struggling to understand why popular browsers seem to handle the definition "new Worker("BarcodeWorker.js")" differently than Android WebView. The original code for this Barcode Reader is from Eddie Larsso ...

What is the reason for the prefixing of dependencies in package.json with @polymer?

As I examine this package.json, I notice that there are two different versions of sinonjs listed: "dependencies": { "@polymer/sinonjs": "^1.14.1", ... "sinon": "^2.3.5", ... }, I am curious about the distinction between sinon and @pol ...

Error occurred during Apple Login using Next_Auth: OAuthCallback issue

Attempting to log in with Apple using NextAuth. Authentication is successful, but it redirects to /?error=OAuthCallback. The URL being used is: https://appleid.apple.com/auth/authorize?client_id=com.wheeleasy.org&scope=name%20email&response_type= ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

How can I implement a Dynamic Input field using Angular?

Suppose there is an input field where a user enters an ID. Once the user clicks the "add" button, I need to send a request to my server to fetch a "name". Afterwards, I want to disable the text input field, hide the "add" button, and show a number input fi ...

Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript. To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images. Here is the project structure: https://i.stack.imgur.com/xfIYD.pn ...

Module 'framer' missing even after removing node modules directory

While cleaning up the angular code, I decided to delete some unused custom modules. However, after doing so, I encountered an error regarding a deleted imported component in app.module.ts even though it had already been removed from the imports. To addres ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

Loading elements of a webpage in a consecutive order

I am currently working on implementing a content slider within my Django application. The specific slider that I am using can be found at this link. One challenge that I am facing is the need to load close to one hundred 'contentDiv' pages, and I ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

To make table headers remain stationary as the data scrolls with JavaScript

When using Explorer, I was able to fix the "thead" part of my table while scrolling by using CSS expressions. The following CSS code snippet showcases how it's done: .standardTable thead tr { position: relative; top: expression(offsetParent.scrollTo ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

Utilizing Vue's dynamic component feature to create event listeners

Issue: My current project involves creating a versatile table component that can be utilized by other components to display tabular data. Each cell in this table could contain one of three possible values: Text HTML Component While I have successfully im ...

The HTML document requests information from a JSP file

I am faced with a situation where I have an HTML page stored on my local computer and a JSP file located on a remote server. My current challenge is: How can I showcase the content from the JSP file on the HTML page? The HTML page is strictly HTML-based ...

The then() function in Node.js is triggered before the promise is fully resolved

I'm struggling to get my Promise function working as intended. Here's what I need to accomplish: I am receiving file names from stdout, splitting them into lines, and then copying them. Once the copy operation is complete, I want to initiate oth ...