14

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.

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.