要將CRA創建的JavaScript 項目遷移到 TypeScript ,首先要看下通過npx create-react-app my-app --typescript生成的項目和普通js項目的區別
1. 從項目目錄上看,除了后綴更改為.tsx之外,還新增加了兩個文件(根目錄下)
1⃣️ src/react-app-env.d.ts
/// <reference types="node" /> /// <reference types="react" /> /// <reference types="react-dom" /> declare namespace NodeJS { interface ProcessEnv { readonly NODE_ENV: 'development' | 'production' | 'test'; readonly PUBLIC_URL: string; } } declare module '*.bmp' { const src: string; export default src; } declare module '*.gif' { const src: string; export default src; } declare module '*.jpg' { const src: string; export default src; } declare module '*.jpeg' { const src: string; export default src; } declare module '*.png' { const src: string; export default src; } declare module '*.webp' { const src: string; export default src; } declare module '*.svg' { import * as React from 'react'; export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; const src: string; export default src; } declare module '*.module.css' { const classes: { readonly [key: string]: string }; export default classes; } declare module '*.module.scss' { const classes: { readonly [key: string]: string }; export default classes; } declare module '*.module.sass' { const classes: { readonly [key: string]: string }; export default classes; }
2⃣️ tsconfig.json
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react" }, "include": [ "src" ] }
2. 從webpack配置上看,CRA已經幫我們考慮了很多了!我們不需要花太多的時間在webpack配置上
//config/webpack.config.js const useTypeScript = fs.existsSync(paths.appTsConfig);
webpack.config.js文件中,會先檢測是否在項目根目錄下存在tsconfig.json文件,有的話啟動對應的webpack配置
補充一下,js項目如果為將文件的后綴補全,webpack打包的時候是不會去嘗試查找對應的ts文件
resolve: { extensions: paths.moduleFileExtensions .map(ext => `.${ext}`) .filter(ext => useTypeScript || !ext.includes('ts') }
比較了兩者的區別,我們現在可以很容易的將js項目遷移至ts項目
1. 安裝對應的依賴
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
2. 為了穩妥,將node_modules全部刪除,重新npm install;完成后,執行npm run start ; CRA會動態將上述兩個文件添加
切記!!別自己手動添加這兩個文件,重新npm install的時候,可能會有版本依賴,安裝的包版本可能也不同
3. 如何做到js和tsx文件共存,其實tsconfig.json文件中的"allowJs": true 就已經做了此操作
注意:你的react-scripts版本至少要為2.1.0
