2017-04-20 79 views
1

我試圖從node_modules導入外部模塊通過只是在做:如何使用節點模塊,而不分型從打字稿

import { offline } from 'redux-offline'; 

從文件/src/store/store.ts。不過,我得到以下錯誤:

Cannot find module redux-offline

我讀過,我們可以聲明一個模塊,就如同redux-offline.d.ts我們定義排序的虛擬聲明,我們可以再從我們的源代碼使用。然而,我完全不明白:

  • 在哪個文件夾中應該定義該文件?
  • Typescript如何知道該模塊正在聲明外部模塊的接口?

我很感謝您的幫助,以瞭解它是如何工作的。

回答

4

In which folder should that file be defined?

這些文件可以真正在任何文件夾中聲明,但最好將它們放在一起描述它們的目錄中。在我們的項目中,我們有一個名爲「ambient-types」的文件夾,其中有一個「external-modules」文件夾。

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

你說得對,這將外部模塊文件夾中坐。

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

在你是我們宣佈了所謂的環境宣言,它看起來如下終極版 - offline.d.ts文件:

declare module 'redux-offline'; 

終極版脫機現在可從進口你自己的文件。

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

這主要是告訴打字稿,在運行時您預計會有一個文件/庫稱爲終極版脫機可用。請注意,導入將具有「任何」類型。

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.html https://www.typescriptlang.org/docs/handbook/modules.html