我阅读了TypeScript模块解析的工作原理。

我有以下存储库:@tsstack/di。编译后,目录结构如下:

├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json

在package.json中,我写了“main”:“dist/index.js”。

在Node.js中,一切正常,但TypeScript:

import {Injector} from '@ts-stack/di';

找不到模块“@ts stack/di”的声明文件/path/to/node_modules/@tsstack/di/dist/index.js”隐式具有“any”类型。

然而,如果我按如下方式导入,那么一切都正常:

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

我做错了什么?


当前回答

import { io, Socket,SocketIOClient } from 'socket.io-client';

在component.ts之上添加这个在我的案例中是有效的。

其他回答

在许多项目中,我面临着许多包的相同问题。所以我创建了Declarator,一个自动生成类型声明的npm包。

它基本上通过在后台运行tsc-emitDeclarationOnly来工作。

您可以从npm安装它:

npm install --save-dev declarator
yarn add -D declarator

然后创建一个简单的声明器.json文件:

{
  "$schema": "https://raw.githubusercontent.com/ArthurFiorette/declarator/master/schema.json",
  "packages": ["package1","package2"]
}

并创建一个脚本来运行它:

使用postinstall脚本将在每次安装包时运行它,这可能很有用

{
  "scripts": {
    "postinstall": "declarator"
  }
}

它不会生成强大的类型,在这一过程中您可能会遇到许多类型,但使用它比不使用它要好得多

阅读更多信息:https://github.com/ArthurFiorette/declarator#readme

我已经尝试了这里的一切,但对我来说,这是一个完全不同的问题:我必须从*.d.ts中删除任何导入语句:

import { SomeModuleType } from '3rd-party-module';

删除错误后。。。

澄清:当我们在*.d.ts文件中声明一个模块时,Typescript编译器会自动将其作为环境模块(不需要显式导入的模块)。一旦我们指定了导入。。。从…起该文件现在成为一个正常(ES6)模块,因此不会自动拾取。因此,如果您仍然希望它作为环境模块,请使用不同的导入样式,如下所示:

type MyType: import('3rd-party-module').SomeModuleType;

还有两种解决方案

如果模块不是您的,请尝试从@types安装类型:

npm install -D @types/module-name

如果出现上述安装错误,请尝试更改import语句以要求:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

对于阅读本文的其他人,请尝试将.js文件重命名为.ts

编辑:您还可以将“allowJs”:true添加到tsconfig文件中。

一个简单的解决方案:

// example.d.ts
declare module 'foo';

如果要声明对象的接口(推荐用于大型项目),可以使用:

// example.d.ts
declare module 'foo'{
    // example
    export function getName(): string
}

如何使用?易于理解的

const x = require('foo') // or import x from 'foo'
x.getName() // intellisense can read this