Lauren Yim
Lauren Yim

Reputation: 14078

How do I type a JS file in node_modules?

I installed module foo which has this package.json:

{
  "name": "foo",
  "version": "0.0.1",
  "exports": {
    ".": ["./index.js"]
  },
  "types": "./index.d.ts"
}

foo comes with its own types for the module entry point. However, I need to import bar.js from foo. Because it isn't exported in index.js, I have to do this:

import {bar} from './node_modules/foo/bar'

This is because if I use import bar from 'foo/bar', I get the error Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './bar' is not defined by "exports" in /path/to/project/node_modules/foo/package.json.

I have typed foo/bar like this:

export const bar: 'bar'

Where would I put this file and what will I need to put in my tsconfig.json?


I've already tried putting my typings in ./types/foo/bar.d.ts and using "typeRoots": ["node_modules/@types", "./types"] in my tsconfig compilerOptions, but TS couldn't find my declaration file:

Could not find a declaration file for module './node_modules/foo/bar'. '/path/to/project/node_modules/foo/bar.js' implicitly has an 'any' type.

I've also tried /// <reference types="./types/foo/bar" />, but the same error persisted.

If I wasn't typing a file from an npm module, I would have just put the types in ./node_modules/foo/bar.d.ts, but I don't want to manually put anything in node_modules.

Upvotes: 0

Views: 447

Answers (1)

Lauren Yim
Lauren Yim

Reputation: 14078

As a temporary solution, I put all my types in ./typings and added this to scripts in my package.json:

"prepare": "for f in typings/**/*; do cp \"$f\" \"node_modules/${f#*/}\"; done"

Upvotes: 0

Related Questions