Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

typescript - Typing an NPM package with no types

The package babel-merge doesn't have type declarations so I'm trying to provide them myself, in a file called babel-merge.d.ts. Here are the relevant files:

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "rootDir": "./src",
    "outDir": "./lib"
  },
  "include": [
    "babel-merge.d.ts",
    "src/**/*.ts"
  ]
}

babel-merge.d.ts

import { BabelConfig } from '@babel/core';
import { Options as DeepMergeOptions } from 'deepmerge';

declare module 'babel-merge' {
  declare function merge(
    source: BabelConfig,
    overrides: BabelConfig,
    deepMergeOpts?: DeepMergeOptions
  ): BabelConfig;

  export default merge;
}
import merge from 'babel-merge';
// "Could not find a declaration file for module 'babel-merge'

The strangest thing is that I have a project which has a very similar configuration that works just fine.

I try to do this sort of thing all the time, and every time I get this sort of error. I invariably spend hours researching typescript configuration and fiddling with my configuration until I randomly get it to work. Is there some obvious solution that I just missed somehow? (I've read the TypeScript documentation on declaration files.)

EDIT:

Here's my second attempt. This time, I tried to use "typeRoots" in my tsconfig.json using this answer as a guide. Yet, the error persists.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "rootDir": "./src",
    "outDir": "./lib",
    "typeRoots": [
      "typings",
      "node_modules/@types"
    ]
  }
}

babel-merge.d.tstypings/babel-merge/index.d.ts

import { BabelConfig } from '@babel/core';
import { Options as DeepMergeOptions } from 'deepmerge';

declare function merge(
  source: BabelConfig,
  overrides: BabelConfig,
  deepMergeOpts?: DeepMergeOptions
): BabelConfig;

export default merge;
import merge from 'babel-merge';
// "Could not find a declaration file for module 'babel-merge'
question from:https://stackoverflow.com/questions/65911268/typing-an-npm-package-with-no-types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...