简体   繁体   中英

How to use an node module without typings from Typescript

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

import { offline } from 'redux-offline';

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

Cannot find module 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. 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?

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.

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

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

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

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 will now be available for import from your own files.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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