Embed images within the JavaScript bundle

Here is my scenario:

I have developed a components library for React. Within this library, there is a package bundled with Rollup that contains various assets, including a GIF picture used in one of the components.

The specific component utilizing this picture looks like so:

import React from 'react';
import PropTypes from 'prop-types';
import ui_spinner from '../../../assets/ui_progress.gif';

/**
 * CircularSpinner
 * Displays a spinner to indicate loading state
 */
class CircularSpinner extends React.PureComponent {
  static propTypes = {
    /** Width of the spinner */
    width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    /** Height of the spinner */
    height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    /** Custom style overrides */
    style: PropTypes.object,
  }

  static defaultProps = {
    width: 128,
    height: 128,
    style: {},
  }

  render() {
    const { style, width, height } = this.props;

    return (
      <img src={ui_spinner} width={width} height={height} style={style} alt="ui_progress" aria-busy="true" />
    );
  }
}

export default CircularSpinner;

After building the project, everything seems fine.

Next, I am working on a React application created using create-react-app and want to test the components library. To achieve this, I utilize npm link to avoid deploying the npm package each time. While the components function correctly within the testing application, the image (the GIF within CircularSpinner) fails to appear.

Hence, my query lies in: How can I include assets in a JavaScript bundle using Rollup? Is my current approach appropriate?

This is my Rollup configuration:

import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import url from 'rollup-plugin-url'

const config = {
  input: 'src/index.js',
  external: ['react'],
  output: {
      format: 'umd',
      name: 'react-components',
      globals: {
          react: "React"
      }
  },
  plugins: [
    babel({
      exclude: "node_modules/**"
    }),
    uglify(),
    url(),
  ]
}
export default config

I execute the build process using rollup -c -o dist/index.js.

The contents of the 'dist' folder after compilation are as follows:

dist/
  assets
    92be5c546b4adf43.gif
  index.js

In the testing application, the image reference looks like this:

<img src="92be5c546b4adf43.gif" width="128" height="128" alt="ui_progress" aria-busy="true">

Any assistance would be greatly appreciated!

Regards, Damien

Answer №1

I have successfully resolved the issue at hand and wanted to share my solution in case it could benefit someone else:

To address the problem, I made adjustments to my rollup configuration by incorporating the rollup-plugin-img. Although I had previously integrated this plugin, my setup was not configured correctly:

The accurate configuration is outlined below:

import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import image from 'rollup-plugin-img'

const config = {
  input: 'src/index.js',
  external: ['react'],
  output: {
      format: 'umd',
      name: 'react-components',
      globals: {
          react: "React"
      }
  },
  plugins: [
    babel({
      exclude: "node_modules/**"
    }),
    image({
      limit: 100000,
    }),
    uglify(),
  ]
}
export default config

The mistake I made was related to the size of my GIF file, which exceeded the default limit of 8192 bytes. This resulted in the following error:

Error: Could not load <path of image> (imported by <path of component that use image>): The "path" argument must be of type string. Received type undefined

Upon adjusting my configuration to raise the limit, everything functioned as expected.

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

Go back to the previous operation

Utilizing ajax to verify if a username is available by checking the MySQL database. If the username is already taken, it will return false to the form submit function. index.php $("#register-form").submit(function(){ var un = $("#un").val(); $.aj ...

JavaScript based Yaml and Swagger linter and validator tool available on npm

Currently, I am involved in a project where we are managing version control of a .yml file that is crucial for defining our API. Unfortunately, there is no consistent linting standard in place because team members are using different editors and tools. I ...

Tips for choosing and deselecting data using jQuery

Is there a way to toggle the selection of data in my code? Currently, when I click on the data it gets selected and a tick image appears. However, I want it so that when I click again on the same data, the tick will disappear. How can I achieve this func ...

Angular JS - Establishing a Connection to Woocommerce OAuth v1

I'm having trouble authenticating myself with the rest service. I attempted to use this library to generate all the necessary parameters as mentioned here, and I constructed the request like this: $scope.oauth = new OAuth({ consumer: { p ...

Guide to deploying a React application - paths requiring adjustments

I am a novice developer looking to learn more. Recently, I decided to clone Emilio Quintanas Servitodo APP into my own repository. After downloading the repo, I attempted to use gh-pages with npm to build and deploy the APP. However, I encountered an issue ...

Using MongoDB's MapReduce feature along with the Date and % operator

I am encountering an issue with a Python script that I am using to aggregate large collections into smaller pieces and group them by timestamp. map = Code("function(number) {" "emit({" "ts : new Date(new Date((this.ts - (this.ts % (60 * number ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

I am trying to figure out how to properly utilize server-only functions within Next.js middleware

In my current project, I am utilizing Next.js 13 along with the App Router feature. While attempting to include a server-specific fetch function in middleware.js, an error message is encountered: Error: Unable to import this module from a Client Compone ...

Why do some button clicks not trigger a page refresh in JavaScript?

Hey there, I have a situation where I have two buttons - one to add a dog to the dog list and another to clear the entire list. Both buttons are functioning properly, but I'm having an issue with only the OnSubmit button refreshing the page. The dog ...

Mocha maintains the integrity of files during testing

After running a unit test to update a config file, I noticed that the file was altered. My initial thought was to use "before" to cache the file and then restore it with "after". mod = require('../modtotest'); describe('Device Configuratio ...

It appears that the TinyMCE Table of Contents plugin has been deactivated

Currently, I am attempting to integrate a Table of contents plugin into my TinyMCE 5 editor. Utilizing react and housing the TinyMCE within a reactstrap modal. When adding other plugins, they function as expected. However, when introducing the Table of con ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

Struggling to resolve my issue using npm install

Encountering an issue with npm. The error message I received is below. More details can be provided upon request as I am not sure what the problem is. I tried searching for a solution online but could not find any similar errors. Is there a documentation a ...

Tips for avoiding repetitive querying when using server-side rendering and dynamic metadata

I have implemented Next.js 13 with the App routing system, as shown in the code. I have a SSR function called FetchingProduct which calls an API to generate dynamic metadata and send data props to a client page component. There is a concern that the fetc ...

Some Firebase functions are being blocked by CORS policy restrictions

When working with FireBase cloud functions, I encountered a CORS policy error that only occurs with certain methods. For instance, my GET and POST requests work perfectly fine, but when attempting to delete or edit an object, the CORS policy error immediat ...

What is the best way to utilize node-sass in a complex and deeply nested directory system?

When it comes to using node-sass from the command line, the documentation can be quite basic. Personally, I am looking into utilizing NPM Scripts as my build tool. In my project, I have various components organized by feature, each in its own folder. Thes ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Travis CI: encountering difficulties while attempting to update npm to a newer version

Attempting to update the npm version being used by Travis CI in the .travis.yml configuration file: language: node_js node_js: 0.12 before_install: npm install -g npm@latest However, after checking the logs of the Travis job, it seems that nothing has ch ...

The NextJS development server is frequently losing connection

Issue While working on my NextJS project, I've been experiencing occasional disruptions with my development server. Whenever I update my code, I encounter random occurrences of the dev server disconnecting and displaying the error message below: Type ...