Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js:

import image from 'rollup-plugin-image'
...
plugins: [
        image(),
        json(),
        resolve(),
        commonjs(),
        typescript({
            typescript: require('typescript'),
        }),
        (process.env.BUILD === 'production' ? terser() : {})

This is what I have in my source:

import CAR_IMAGE from "../resources/expand.png";

But I keep getting an error from the rtp2 plugin which reads:

Semantic error TS 2307, cannot find a module "../resources/expand.png"

What's strange is that I encounter the same issue with different image-loading plugins for Rollup. The path is correct, the image is there. This error is driving me crazy =((

Update: I have created a repository to reproduce this bug:

https://github.com/AntonPilyak/rollup-image-bug

Update 2: I have reported these bugs:

https://github.com/rollup/rollup-plugin-url/issues/22

https://github.com/alwaysonlinetxm/rollup-plugin-img/issues/5

https://github.com/rollup/rollup-plugin-image/issues/10

Why is it so frustratingly difficult? =(((

Answer №1

To update your rollup configuration file, replace the rollup-plugin-image package with this package. Then, include the following code snippet in the plugins section:

plugins: [
image({
  extensions: /\.(png|jpg|jpeg|gif|svg)$/,
  limit: 10000
}),........

After making these changes, create a file named declaration.d.ts in the root of your project and add the following snippet:

declare module '*.png' {
    const value: any;
    export default value;
}

Don't forget to include the declaration file in your tsconfig.json:

"include": ["src","src/declaration.d.ts"],

Finally, re-run rollup in CLI and everything should work smoothly!👍

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

What does an exclamation mark signify in Angular / Type Script?

Being a newcomer in the world of front end development, I am currently teaching myself Angular (11.2.10). While exploring a sample project, I noticed this particular piece of html template code written by another person and utilized in multiple places: < ...

Challenges with Spreading Props in TextField Component After MUIv4 Upgrade with TypeScript

Latest Material-UI Version: 4.1.0 I'm encountering difficulties in passing props to an abstracted <TextField /> component that I've developed. Below is the snippet of code: PasswordInput.tsx import * as React from 'react' impo ...

Error encountered with TypeScript template literals strings type

There's a new feature in the latest version of Typescript that allows the use of template literal strings as types, like this: type Hey = 'Hey'; type HeyThere = `${Hey} There`; It works perfectly in the Typescript playground with version 4 ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Arranging an array of integers followed by sorting by the decimal part of each value in a particular sequence using JavaScript

Below is an example of sorting an array: let arr = ['100.12', '100.8', '100.11', '100.9']; When sorted traditionally, the output is: '100.11', '100.12', '100.8', '100.9' Ho ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

Styles are not applied by Tailwind to components in the pages folder

NextJS project was already created with tailwind support, so I didn't have to set it up myself. However, when I add className to an HTML element in a component within the pages/ folder, it simply doesn't work, even though the Elements panel in D ...

Tips for transferring request variables/data from a middleware to another function in typescript

I need to authenticate a user's jwt token using middleware. This is the middleware I have: const authorized = (req: Request, res: Response, next: NextFunction) => { const token = req.header("token") if(!token){ return res.send("N ...

Tips for fixing type declaration in a generic interface

Here is a simple function that constructs a tree structure. interface CommonItem { id: string parent: string | null } interface CommonTreeItem { children: CommonTreeItem[] } export const generateTree = <Item extends CommonItem, TreeItem extends ...

What exactly does "context" refer to in the context of TypeScript and React when using getServerSideProps?

As a beginner in coding, I have a question regarding a specific syntax I recently encountered. I am confused about this particular line of code and couldn't find any helpful explanations online: export async function getServerSideProps(context: GetSer ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Fixing the "Cannot find name" error by targeting ES6 in the tsconfig.json file

I recently started learning AngularJS through a tutorial. The code repository for the tutorial can be accessed at this link. However, upon running npm start using the exact code provided in the tutorial, I encountered the following error: Various TS2304 e ...

The confirm alert from Material UI is being obscured by the dialog

How can I ensure that a material ui dialog does not hide the alert behind it when confirming an action? Is there a way to adjust the z index of the alert so that it appears in front of the dialog? import Dialog from "@material-ui/core/Dialog"; i ...

EmotionJS Component library's Component is not able to receive the Theme prop

I am in the process of developing a component library using Emotion and Typescript. However, I have encountered an issue when trying to import the component into a different project that utilizes EmotionJS and NextJS - it does not recognize the Theme prop. ...

Having difficulties in TypeScript identifying types within a project containing multiple node_modules directories

I am currently in the process of transitioning a codebase from Flow to TypeScript. I am encountering an issue with the error message Cannot find module 'SOME DEPENDENCY' or its corresponding type declarations.ts(2307) for several dependencies tha ...

Using Typescript and webpack to detect variables that are defined in the browser but not in Node environment

My goal is to create a package that can be used on both servers and clients with minimal modifications required. Some libraries are available in Node but not in a browser, while others are accessible in a browser but not in Node. For instance, when utili ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Troubleshooting the order of Javascript execution in bundled TypeScript applications

I encountered an issue with the execution order of generated JavaScript code during bundling, resulting in an error message when everything is bundled together. An error occurred: [$injector:nomod] Module 'app.demo' is not accessible! This cou ...

The parameter type '(req: Request, res: Response, next: NextFunction) => void' does not match the type of 'Application<Record<string, any>>'

I'm currently working on an Express project that utilizes TypeScript. I have set up controllers, routers, and implemented a method that encapsulates my controller logic within an error handler. While working in my router.ts file, I encountered an err ...

Setting the default value for Angular Material's select component (mat-select)

Many inquiries are focused on setting a default value to display in a "Select" control. In this particular case regarding Angular 8 template driven forms, the issue lies in the inability to show the default value in the mat-select when the button is clicke ...