我阅读了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 * as html2pdf from 'html2pdf.js';

注释代码,将以下脚本文件保存在index.html中,如官方文档中所示。

<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>

并在正在使用的组件中声明html2pdf变量。

declare var html2pdf: any;

就是这样。我在这个问题上纠结了两天,但最终得到了解决。

其他回答

从Typescript文档中:

注意,“typings”字段与“type”同义,也可以使用。

还要注意,如果主声明文件名为index.d.ts,并且位于包的根目录(index.js旁边),则不需要标记types属性,尽管这样做是明智的。

由于某种原因,我的“types”属性指向一些main.d.ts。从package.json中删除该行,它开始工作。

如果导入不适用于您

import * as html2pdf from 'html2pdf.js';

注释代码,将以下脚本文件保存在index.html中,如官方文档中所示。

<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>

并在正在使用的组件中声明html2pdf变量。

declare var html2pdf: any;

就是这样。我在这个问题上纠结了两天,但最终得到了解决。

您可能需要创建扩展名为.d.ts的文件。

将此文件名推送到tsconfig.json文件的include键下:

  "include": [
    "src",
    "index.d.ts"
  ]

这应该是工作

不幸的是,包编写者是否对声明文件感到困扰,我们无法控制。我倾向于创建一个像index.d.ts这样的文件,其中包含各种包中所有缺失的声明文件:

索引.d.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

并在tsconfig.js中引用它:

"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "index.d.ts" // this
  ]

一个简单的解决方案:

// 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