Retrieve resources from a pre-built npm package on-the-fly

Question regarding the creation of npm packages and the ability to dynamically request resources from one package in another.

Imagine I have a collection of images in package A, along with JavaScript logic to fetch them:

// Inside package B
import Component from 'pkg-a'

Component.getImage('foo')

I build this using vite/webpack and then use package B, which has package A listed in its dependencies in 'package.json'

Typically, the build tool will only include the specified images directly into the /dist folder of package A

However, my goal is to:

  1. Have all images in the /dist folder - this can be achieved by using the /public folder;
  2. Enable package A to accept arguments specifying an image name and return the correct image dynamically from its dist folder - unsure if this is feasible;

Is it possible to request just one image from package A, or do I need to encode all images in BASE64 format inside .es.js files (which increases file size by 30%) within package A?

Answer №1

To achieve the desired result, I would implement the following steps. While I am not entirely certain about how it can be accomplished with vite (specifically for step 2), I will detail my approach using webpack. The overarching concept, however, remains applicable in both scenarios.

  1. Within package A, I would establish a function (likely within the main index.js) that accepts the image name as a parameter and returns the corresponding image path. This function leverages dynamic imports.
    export function getImage(name) {
       return import(`./images/${name}.png`);
    }
    
  2. Subsequently, I would configure webpack within package A to copy the images to the dist directory.
    // webpack.config.js for package A
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    module.exports = {
      // Other configurations ...
      plugins: [
        new CopyWebpackPlugin([
          { from: 'src/images', to: 'images' },
        ]),
     ],
    };
    
  3. Finally, in package B, I would import the getImage function from package A and utilize it to retrieve the image (a simplified example that can be tailored to suit your framework or requirements).
    
    import { getImage } from 'pkgA';
    
    async function loadComponent() {
      const imgSrc = await getImage('myRequiredImg');
      const img = new Image();
      img.src = imgSrc.default;
      document.body.appendChild(img);
    }
    
    loadComponent();
    

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

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

Can the fluctuations in resolution of webRTC streaming video be detected?

We are currently working on a project involving WebRTC and have specific requirements that involve detecting when the resolution of the streaming video (remote stream) changes in WebRTC. Is there a way for us to achieve this? Any tips or guidance would be ...

Issue with alignment in the multiselect filter of a React data grid

In React Data Grid, there is a issue where selecting multiple filter options messes up the column headers. Is there a solution to display selected filter options above a line in a dropdown rather than adding them to the column header? The column header siz ...

What is preventing me from retrieving WP custom fields value or post ID using Ajax?

After successfully generating a link based on the visitor's location, I encountered an issue with caching when using full-page caching. To address this problem, I decided to implement AJAX to dynamically load the link. While my code worked well in ret ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

What is the best way to save npm configuration settings to the .npmrc file within a project

My goal is to utilize npm config in order to specify values in a project's .npmrc file. Unfortunately, the documentation does not provide guidance on how to designate a specific file to save these values into. I am in need of a command similar to np ...

Using the foreach loop within the Alert.alert function in React Native

function displayModal(modalarray) { return Alert.alert( "Modal Title", "Alert Message", [ modalarray.forEach(element => { "{text: element, onPress: () => console.log('button press)},"; }) ], ...

Establishing seamless transitions between various interfaces within my application

Hello everyone, I am developing an app in React Native and I have successfully implemented a login system. However, I am facing issues with routing between different screens. For example, I have distinct flows such as the signup flow: 1) User enters phone ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

I'm attempting to streamline my code...what is preventing me from achieving this?

As someone who is self-taught in the ways of coding, I'm looking to streamline my JavaScript code. I have two divs with classes a0 and a1, and I want to add a mouseenter event to each one (using the same event). You can check out my JSFiddle for a be ...

Mastering the manipulation of complex nested objects within React state

Welcome, fellow developers! I am a junior developer currently working on a project that involves a large nested object structure (see example below). I am looking for the best approach to use this as a React state that can be accessed from multiple compon ...

Exploring the Concept of Class Inheritance in Javascript

I've been thinking about how to implement Class Inheritance in JavaScript. Since JavaScript doesn't have classes like other languages, we typically use functions to create objects and handle inheritance through Prototype objects. For instance, h ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

Encountering a problem with binding parameters while trying to submit JSON data to an MVC controller along with

I am currently struggling with posting a JSON object to an ASP.NET MVC controller without using Ajax. I have tried various methods but have not been successful so far. Here is what I have attempted: Backend Parameter Object public class Person { ...

What restrictions prevent the use of npm packages in a Meteor project?

Incorporating a npm package into my meteor project is something I need to do (e.g. the 'moment' package). To achieve this, I initiated the following command: meteor npm install --save moment . This led to an update of the dependencies in package ...

Create a function within jQuery that triggers when an option in a select field is chosen

As I edit a podcast, I have encountered a situation where an option is being selected through PHP code. Now, I am looking to implement jQuery functionality for when the option is selected from the select field. I have searched through various questions an ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...