Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules?

Code:

import { t2 } from "./t1.js"
t2.hello();

import { mat4 } from "./node_modules/gl-matrix/esm/index.js";
mat4.create();

Error:

main.ts:4:22 - error TS7016: Could not find a declaration file for module './node_modules/gl-matrix/esm/index.js'. '/.../node_modules/gl-matrix/esm/index.js' implicitly has an 'any' type.

4 import { mat4 } from "./node_modules/gl-matrix/esm/index.js";
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If I comment out the last two lines, it compiles without errors.

To reproduce the issue, follow these steps:

npm install --save-dev typescript gl-matrix

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "outDir": "./obj",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "allowJs": true
  }
}

t1.js (simulates the content of index.js from gl-matrix):

import * as t2 from "./t2.js"
export { t2 };

t2.js (resembles the content of mat4.js from gl-matrix):

export function hello() {
    return "hello";
}

Answer №1

When using an import statement, it is important to avoid including the term node_modules, as this directory name should not be directly referenced. Instead, consider utilizing an import map in a browser environment or importing built-in modules in a Node environment with identifiers like 'node:fs'.

The error message stating,

Could not find a declaration file for module './node_modules/gl-matrix/esm/index.js'. [It] implicitly has an 'any' type.

is simply TypeScript informing you that it lacks type definitions for the mentioned module, which is expected when bypassing the usual package structure by directly accessing a file such as this one.

To properly handle this situation, ensure you import specific components using syntax like import {mat4} from "gl-matrix";. By doing so, the compiler will determine the appropriate module format and locate relevant type definitions, such as those found in the types.d.ts file.

If you opt to copy the file into your project directory and then import it, TypeScript will analyze it similarly to your own code, leveraging any JSDoc comments present in the ESM modules of gl-matrix (like those in this example) to infer types effectively.

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

Customize the appearance of your apps script using conditional formatting to highlight values that are

https://i.stack.imgur.com/L1KFZ.png I need to create an array of all 50 US states based on the abbreviations in a column. The goal is to compare each cell against the array and if it doesn't match, format it red. After researching conditional format ...

What are the typical situations in which Node.js is commonly used?

Do you believe that a majority of node.js users primarily utilize npm? What do you think are the most prevalent use cases for node.js apart from npm? ...

Error message: The login buttons from Meteor's accounts-ui-bootstrap-3 are not showing up on the webpage

Following the installation of bootstrap-3 and accounts-ui-bootstrap-3, the expected ui-accounts login widget was not displayed when using {{ loginButtons }}. Instead, a <div> appeared in place of the widget, with no actual widget visible. Are there ...

Troubleshooting: Issues with locating CSS and JS files (404 error) while utilizing URL parameters within Django platform

I've designed a dashboard page that showcases various graphs. The page automatically updates the graph data every hour. You can access the page at the following URL: http://localhost/dashboard I'd like to give users the option to specify the ...

Compiling errors arise due to TypeScript 2.4 Generic Inference

Experiencing issues with existing TypeScript code breaking due to changes in generic inference. For instance: interface Task { num: number; } interface MyTask extends Task { description: string; } interface Job {} type Executor<J> = <T ...

Saving URI from HTTP request in Javascript using Google Drive API: A step-by-step guide

I'm struggling to understand and implement the instructions provided at https://developers.google.com/drive/v3/web/manage-uploads#save-session-uri While I've successfully used javascript to upload files to Google Drive, I am now faced with a cha ...

Strange behavior observed in the Datepicker, possibly linked to the blur event

I'm facing a challenge with the Datepicker feature. When I blur, the calendar disappears if the Datepicker was active, but the focus remains on the input field. As a result, I am unable to trigger the Datepicker again by clicking on the input field. T ...

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Transform JavaScript Object into an unformatted string

Is there a way to convert a JavaScript object to the following format? I require a backward slash before every double quote. Here is the input: {key1: "value1", key2: "value2"} And the desired output is: '{key1: \"valu ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

What is the best way to get process.argv to display only the arguments and exclude the node command and path?

As the title suggests, I am working on a substantial project that involves AppleScript and iMessage. After testing the script, it successfully opens Terminal and executes: node ~/Desktop/chatbot [argument]. However, at the moment, all it returns is: [ &apo ...

How to assign attributes to multiple menu items in WordPress without using JavaScript

I'm currently working on adding attributes to each item in my WordPress navbar. Here is what I have at the moment: <ul id="menu-nav-bar" class="menu"> <li><a href="#text">text</a></li> <li><a href="#car ...

Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicat ...

What is the process for setting a Type to a prop in React?

I have a main component: // DashboardComponent.tsx const DashboardComponent = () => { const {loading, error, data} = useQuery(resolvers.ReturnAllMovies); if (loading) return <p>loading</p>; if (error) return <p>Error! ${error.m ...

Unable to send an API request from Postman to a database through express and mongoose technology

This is my server.js: const express= require('express'); const app = express(); // const mongoose= require('mongoose'); // load config from env file require("dotenv").config(); const PORT = process.env.PORT || 4000; // middl ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

The data being transmitted by the server is not being received accurately

Hey there! I've recently started using express.js and nodejs, but I've encountered an issue where my server is sending me markup without the CSS and JS files included. const express = require('express'); const app = express(); const htt ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

What methods can I use to create fresh metadata for a search inquiry?

On my search page, I am using a search API from OpenAI. My goal is to modify the meta description of the page to display 'Search | %s', with %s representing the decoded search query. However, due to limitations in Nextjs 13, the useSearchParams f ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...