我阅读了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';

我做错了什么?


当前回答

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

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

删除错误后。。。

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

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

其他回答

如果需要快速修复,只需将其添加到导入行之前:

// @ts-ignore

一个简单的解决方案:

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

解决方案:您所要做的就是编辑TypeScript Config文件tsconfig.json,并添加一个新的键值对作为

"compilerOptions": {
"noImplicitAny": false
}

@ktretyak和@Retsam的答案是正确的,但我想添加一个完整的实时示例以及我必须做的事情:

错误:

错误TS7016(TS)找不到模块的声明文件'反应区域选择'。'C:/Repo/node_modules/react region select/lib/RegionSelect.js'隐式具有“any”类型。尝试npm i--save dev@types/react region select(如果存在)或添加新声明包含“声明模块”的(.d.ts)文件

运行npm i--save dev@types/react region select时出现错误:

npm错误!代码E404npm错误!404未找到-GEThttps://registry.npmjs.org/@类型%2反应区域选择-未找到npm错误!404'@类型/react-region-select@latest'不是在npm注册表中。npm错误!404你应该让作者发布它(或者自己使用这个名字!)npm错误!404注意您也可以从npm tarball、文件夹、httpurl或giturl安装。

考虑到create-react-app创建了一个名为react-app-env.d.ts的文件,我尝试将声明模块放入“react region select”;但我还是收到了错误。

然后,我在src中创建了一个名为typings的新文件夹,以及名为react-region-select.dts的文件

declare module 'react-region-select';

这样做之后,错误消失了,我可以像文档所述那样导入它:

import RegionSelect from "react-region-select"; 

https://github.com/casavi/react-region-select

这对我有用。

// modules.d.ts 
declare module 'my-module';
// tsconfig.json 
{
  ...
  "include": [
    ...
    "src", "modules.d.ts"
  ]
}

// Import
import * as MyModule from 'my-module'
...
const theModule = MyModule()
...