如何在没有 Typescript 打字的情况下使用节点模块 [英] How to use an node module without typings from Typescript

查看:40
本文介绍了如何在没有 Typescript 打字的情况下使用节点模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下方式从 node_modules 导入外部模块:

I'm trying to import an external module from node_modules by just doing:

import { offline } from 'redux-offline';

来自文件 /src/store/store.ts.但是,我收到以下错误:

From a file /src/store/store.ts. However, I get the following error:

找不到模块redux-offline

我读到我们可以声明一个模块,比如 redux-offline.d.ts,我们在其中定义了一个虚拟声明,然后我们可以从我们的源代码中使用它.然而,我完全不明白:

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. Yet, I don't get it at all:

  • 应该在哪个文件夹中定义该文件?
  • Typescript 如何知道该模块正在声明外部模块的接口?

如果您能帮助我了解它的工作原理,我将不胜感激.

I'd appreciate your help to understand how it works.

推荐答案

应该在哪个文件夹中定义该文件?

In which folder should that file be defined?

这些文件实际上可以在任何文件夹中声明,但是最好将它们放在一个描述它们是什么的目录中.在我们的项目中,我们有一个名为ambient-types"的文件夹,其中有一个external-modules"文件夹.

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.

我读过我们可以声明一个模块,比如 redux-offline.d.ts

I've read that we can declare a module, something like redux-offline.d.ts

你说得对,这将位于 external-modules 文件夹中.

You're right, This would sit within the external-modules folder.

Typescript 如何知道该模块正在声明外部模块的接口?

How does Typescript know that that module is declaring the interface of an external module?

在您的 redux-offline.d.ts 文件中,我们声明了所谓的环境声明,如下所示:

In you're redux-offline.d.ts file we declare what's called an ambient declaration, it would look as follows:

declare module 'redux-offline';

redux-offline 现在可以从您自己的文件中导入.

redux-offline will now be available for import from your own files.

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

这基本上告诉 Typescript,在运行时您希望有一个名为 redux-offline 的文件/库可用.请注意,导入将具有任何"类型.

This basically tells Typescript that at runtime you expect that there will be a file/library called redux-offline available. 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.

更多参考见 - https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.htmlhttps://www.typescriptlang.org/docs/handbook/modules.html

这篇关于如何在没有 Typescript 打字的情况下使用节点模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆