跳至主要內容

新增 TypeScript

注意:這項功能在 react-scripts@2.1.0 及更新版本中提供。

TypeScript 是一個 JavaScript 的強類型子集,它會編譯為純 JavaScript。

安裝

要使用 TypeScript 開始一個新的 Create React App 專案,您可以執行

npx create-react-app my-app --template typescript

yarn create react-app my-app --template typescript

如果您先前已透過 npm install -g create-react-app 全域安裝 create-react-app,我們建議您使用 npm uninstall -g create-react-appyarn global remove create-react-app 解除安裝此套件,以確保 npx 始終使用最新版本。

create-react-app 的全域安裝不再支援。

要將 TypeScript 加入現有的 Create React App 專案,請先安裝它

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

yarn add typescript @types/node @types/react @types/react-dom @types/jest

接下來,將任何檔案重新命名為 TypeScript 檔案(例如,src/index.js 改為 src/index.tsx),並重新啟動開發伺服器

類型錯誤會與建置相同顯示於相同主控台。在繼續開發或建置專案之前,您必須修正這些類型錯誤。有關進階設定,請參閱這裡

開始使用 TypeScript 和 React

不需要建立 tsconfig.json 檔案,系統會為您建立。您可以編輯產生的 TypeScript 設定檔。

疑難排解

如果專案並未在已啟用 TypeScript 的情況下建立,npx 可能正在使用 create-react-app 的快取版本。移除先前安裝的版本,執行 npm uninstall -g create-react-appyarn global remove create-react-app(參閱 #6119)。

如果您目前正在使用 create-react-app-typescript,請參閱 這篇部落格文章,了解如何移轉至建立 React 應用程式。

不支援恆定枚舉和命名空間,您可以在這裡瞭解與 TypeScript 搭配使用 Babel 的限制。