简体   繁体   English

如何在没有Typescript类型的情况下使用节点模块

[英]How to use an node module without typings from Typescript

I'm trying to import an external module from node_modules by just doing: 我正试图通过以下方式从node_modules导入外部模块:

import { offline } from 'redux-offline';

From a file /src/store/store.ts . 从文件/src/store/store.ts However, I get the following error: 但是,我收到以下错误:

Cannot find module redux-offline 找不到模块redux-offline

I've read that we can declare a module, something like redux-offline.d.ts where we define sort of a dummy declaration that we can then use from our source code. 我已经读过我们可以声明一个模块,比如redux-offline.d.ts ,我们定义了一个虚拟声明,然后我们可以从源代码中使用它。 Yet, I don't get it at all: 然而,我根本得不到它:

  • In which folder should that file be defined? 应该在哪个文件夹中定义该文件?
  • How does Typescript know that that module is declaring the interface of an external module? Typescript如何知道该模块正在声明外部模块的接口?

I'd appreciate your help to understand how it works. 感谢您的帮助,了解它的工作原理。

In which folder should that file be defined? 应该在哪个文件夹中定义该文件?

The files could really be declared in any folder however, it's good to put them together, in a directory that describes what they are. 这些文件实际上可以在任何文件夹中声明,但最好将它们放在一起,描述它们是什么。 In our projects, we have a folder called "ambient-types" and within that we have an "external-modules" folder. 在我们的项目中,我们有一个名为“ambient-types”的文件夹,其中有一个“external-modules”文件夹。

I've read that we can declare a module, something like redux-offline.d.ts 我已经读过我们可以声明一个模块,比如redux-offline.d.ts

You're right, This would sit within the external-modules folder. 你是对的,这将位于external-modules文件夹中。

How does Typescript know that that module is declaring the interface of an external module? Typescript如何知道该模块正在声明外部模块的接口?

In you're redux-offline.d.ts file we declare what's called an ambient declaration, it would look as follows: 在你的redux-offline.d.ts文件中,我们声明了所谓的环境声明,它看起来如下:

declare module 'redux-offline';

redux-offline will now be available for import from your own files. redux-offline现在可以从您自己的文件导入。

import { redux-offline } from 'redux-offline';

This basically tells Typescript that at runtime you expect that there will be a file/library called redux-offline available. 这基本上告诉Typescript,在运行时你希望有一个名为redux-offline的文件/库可用。 Note that the import will have an "any" type. 请注意,导入将具有“任何”类型。

Ambient declarations is a promise that you are making with the compiler. 环境声明是您使用编译器做出的承诺。 If these do not exist at runtime and you try to use them, things will break without warning. 如果这些在运行时不存在并且您尝试使用它们,则事情将在没有警告的情况下中断。

For more reference see - https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html https://www.typescriptlang.org/docs/handbook/modules.html 有关更多参考,请参阅 - https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html https://www.typescriptlang.org/docs/handbook/modules.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM