Achieve compliance with the ESLint "no-var-requires" rule by utilizing an import statement for a module that lacks a declaration file

Within my NodeJS/TypeScript project, I am successfully using fluent-ffmpeg. To utilize it, I have to import the path properties from both ffmpeg-installer/ffmpeg and ffprobe-installer/ffprobe.

The import for ffmpeg appears as follows:

import * as ffmpegInstaller from "@ffmpeg-installer/ffmpeg"; 

This is enabled by the presence of a declaration file named index.d.ts within the @ffmpeg-installer/ffmpeg module's types folder.

However, when it comes to ffprobe, importing is not possible due to the absence of a similar declaration file. If I try:

import * as ffprobeInstaller from "@ffprobe-installer/ffprobe";
, an error occurs:

A declaration file could not be found for module '@ffprobe-installer/ffprobe'. The '<...>/node_modules/@ffprobe-installer/ffprobe/index.js' implicitly has an 'any' type. You can try

npm i --save-dev @types/ffprobe-installer__ffprobe
if available, or add a new declaration (.d.ts) file containing
declare module '@ffprobe-installer/ffprobe';
ts(7016)

Even after running

npm i --save-dev @types/ffprobe-installer__ffprobe
, there is no resolution.

In order to proceed, I use

const ffprobeInstaller = require("@ffprobe-installer/ffprobe");
instead, which effectively works.

Nevertheless, ESLint raises an issue:

The require statement is not part of the import statement. eslint (@typescript-eslint/no-var-requires)

To address this, I attempted to replace it with:

import ffprobeInstaller = require("@ffprobe-installer/ffprobe");
as recommended in the ESLint documentation, but then I encounter the
A declaration file could not be found... ts(7016)
again.

There are several approaches I could take to resolve this problem:

  • Create my own declaration file
  • Disable the no-var-requires rule or ignore it locally

My question is: How can I comply with ESLint's no-var-requires rule without creating a declaration file or disabling the rule?

Answer №1

Approach your issue from two perspectives,

  1. When facing typescript -> Remember to have a declaration file, whether it be through creating your own or installing an existing package
  2. Dealing with eslint -> Opt for an import statement over var-requires.

An intriguing point to note is that require comes with a return type of any. This might lead you to believe that the typescript problem is solved. However, this inherent type functions more like a makeshift declaration file, compromising type restrictions.

interface NodeRequireFunction {
    (id: string): any;
}

To sum up, generating a declaration is essential, whether sourced from a file or implicitly. Eslint, on the other hand, is merely a coincidental inclusion.

Answer №2

The @ffprobe-installer/ffprobe package is written entirely in JavaScript and does not have any type definitions available. If you prefer to use it without specifying types and treat everything as an 'any', one workaround is to create a new declaration file as suggested by the compiler.

declare module '@ffprobe-installer/ffprobe'

For instance, you can create a file named ffprobe.d.ts at the root of your source code directory, include the line above, and the compilation error should disappear.

If you choose to avoid the compilation error by using require instead of import, you may need to disable the ESLint rule using eslint-disable-next-line or a similar approach. Unfortunately, there isn't a way to prevent ESLint from flagging the use of require without turning off the rule somewhere since it's designed to enforce certain coding standards.

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

How did I end up facing two distinct decimal separators side by side like this?

As I find myself in France where the decimal separator is a comma, I have created this component that showcases a discrepancy in displaying numbers: Both commune.population and commune.surface are decimal numbers (with the type number) However, they unexp ...

Angular 14: Removing elements from FormArray causes the remaining elements to lose their values

My form includes custom inputs and utilizes the ControlValueAccessor. To view the implementation, visit this link. I encountered an issue where deleting an item from a FormArray would inadvertently clear the values of the other FormGroups still present in ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

Using Angular 2, you can pass an object as a parameter to a function

Is there a way to pass an object as a parameter in the DOM on this forum? Within my HTML code, I have the following: <div class="list-items"> <ul> <li *ngFor="let i of item"> <span (click)="onAdd({{newUser.us ...

Encountering the error "Unable to use the '+' operator with 'symbol' type when attempting to combine $route.name"

Looking to retrieve the current route name from a template in order to pass it to a router link (specifically passing the current route to the login view so I can redirect users there after authentication). Everything functions as expected, but when perfo ...

Information stored in IndexedDB is not retained permanently

My journey to explore various web technologies (such as HTML, CSS, JavaScript) led me to create a simple web application. To enhance the functionality of my app, I integrated IndexedDB for data storage and operations like insert, update, get and delete. H ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

Encountering a problem with starting npm in React

Every time I attempt to initiate npm start, an error message pops up that leaves me confused about its meaning ...

What is the best way to toggle a card within a collection of cards using Angular?

Wishing you a wonderful day! I simply desire that when I click on a card, only that specific card flips over. But unfortunately, all the cards flip when I click on just one. HTML https://i.sstatic.net/B0Y8F.png TypeScript https://i.sstatic.net/mVUpq.png ...

Managing numerous subscriptions to private subjects that are revealed by utilizing the asObservable() method

I'm using a familiar approach where an Angular service has a private Subject that provides a public Observable like this: private exampleSubject = new Subject<number>(); example$ = this.exampleSubject.asObservable(); In my particular situation, ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

The number of keys in the related object must correspond to the length of the array in Advanced Generic Types

Can we achieve type safety across rows and columns by having one object define the structure of another? Starting Point: export interface TableColumn { name: string; type: "string" | "number" | "action"; id: string; } ...

Issue encountered with dynamic ngStyle variable: ERROR Error: Unable to locate a supporting object 'ngStyleSmall'

I have defined two variables for ngstyle ngStyleSmall = { width: '150px !important', 'max-width': '150px', }; ngStylemedium = { width: '250px !important', 'max-width&apo ...

Is it possible to reference the prior value of a computed Angular signal in any way?

Is it possible to dynamically add new values from signal A to the existing values in signal B, similar to how the scan operator works in RxJS? I am looking for something along the lines of signalB = computed((value) => [...value, signalA()]). Any sugg ...

Changing the names of properties within a intricate JSON structure

I have a JSON data structure that is quite complex, like the one shown below: const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...