char m
char m

Reputation: 8336

Why .d.ts file module declaration doesn't work in angular app?

I have created file called global.d.ts in src folder with following content:

declare module 'ol-contextmenu';

I have also tried to locate it in root, in node-modules/@types but it just doesn't work.

My component imports ol-contextmenu (that doesn't have types) like this:

import ContextMenu from 'ol-contextmenu'; 

I have tried to edit tsconfig.json in multiple ways for the .d.ts file to be found. For example:

"include": [
  "src/global.d.ts"
]

But I always get error:

error TS7016: Could not find a declaration file for module 'ol-contextmenu'. 'C:/dev/nis/NIS/ClientApp/node_modules/ol-contextmenu/dist/ol-contextmenu.js' implicitly has an 'any' type. Try npm install @types/ol-contextmenu if it exists or add a new declaration (.d.ts) file containing declare module 'ol-contextmenu';

5 import ContextMenu from 'ol-contextmenu'; ~~~~~~~~~~~~~~~~

I have also tried to copy the file to node-modules/@types but the error is always same.

Upvotes: 3

Views: 6739

Answers (1)

Jorge J Lorenzo
Jorge J Lorenzo

Reputation: 141

You can take one of the ways declared here in the Typescript's official docs in order to make your Typescript aware that you will be using ECMAScript modules format instead of CommonJs modules format.

In my case I went across the way of creating the index.d.ts file under the src folder of my Angular app, and inside of it, declare all the js files that you need to declare as an ECMAScript module, for example in your case:

declare module 'ol-contextmenu';

Why? Well, as per the doc:

TypeScript replicates the node resolution for modules in a package.json, with an additional step for finding .d.ts files. Roughly, the resolution will first check the optional "types" field, then the "main" field, and finally will try index.d.ts in the root.

Upvotes: 2

Related Questions