1.前提
我用 npx create-react-app my-react-ts-app --template typescript 創建了一個應用,加了typescript到項目中;
問題來了,我在文件引入'react-redux'包,卻紅線提示我:
無法找到模塊“react-redux”的聲明文件
try npm install @types/react-redux
或者 declare module 'react-redux'
import { Provider } from 'react-redux';
2.解決辦法
(根據提示來解決,真是個小機智girl)
方式1: try npm install @types/react-redux ,庫有自己的聲明文件
NPM安裝的格式: npm install @types/<package-name>
這樣很好,因為我們只需要安裝這個庫,就可以立即使用它了。要知道一個庫是否包含類型,看庫中是否有 index.d.ts
文件。
有些庫會在 package.json
文件的 typings
或 types
屬性中指定類型文件。
需要注意的是:該庫包含了自己的聲明文件時只需要安裝就好,如果沒有再從 DefinitelyTyped 獲取它的聲明文件(也就是npm安裝)
方式2: declare module 'react-redux' 自給自足
如果這個庫沒有自己的聲明文件,那么就需要動手創建一個定義文件了
首先在根目錄下創建文件夾‘typings’
再新建文件'react-redux.d.ts'
/typings/react-redux.d.ts
declare module 'react-redux'{
const content: any;
export = content;
}
然后在ts配置文件中加入'typings'
大功告成,噢耶~