将create-react-app从javascript迁移到typescript

要将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. 将上述的两个文件copy到你的本地项目,然后将后续开发的需求用ts编写

3. 如何做到js和tsx文件共存,其实tsconfig.json文件中的"allowJs": true 就已经做了此操作

猜你喜欢

转载自www.cnblogs.com/luguiqing/p/11723617.html