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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47508564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:04:31  来源:igfitidea点击:

Migrating create-react-app from javascript to typescript

javascriptreactjstypescriptcreate-react-app

提问by galvan

I started a react project using create-react-app few months ago and I'm interesting in migrating the project from Javascript to Typescript.

几个月前,我使用 create-react-app 启动了一个 React 项目,我对将项目从 Javascript 迁移到 Typescript 很感兴趣。

I saw that there is a way to create react app with typescript using the flag:

我看到有一种方法可以使用标志创建带有打字稿的反应应用程序:

--scripts-version=react-scripts-ts

But I didn't find any explanation how can I migrate an existing JS project to TS. I need it to be done incrementally so I can work with both .js and .ts files so I can do the transformation over time. Does anyone has any experience with this migration? What are the required steps that should be done to make this work?

但是我没有找到任何解释如何将现有的 JS 项目迁移到 TS。我需要逐步完成,以便我可以使用 .js 和 .ts 文件,以便随着时间的推移进行转换。有没有人有这种迁移的经验?应该采取哪些必要步骤才能使这项工作发挥作用?

回答by galvan

I found a solution to migrate create-react-app from javascript to typescript, this way doesn't requireeject.

我找到了一个将 create-react-app 从 javascript 迁移到 typescript 的解决方案,这种方式不需要弹出。

  1. Create a temporary react project with typescript by running the command create-react-app --scripts-version=react-scripts-ts(Note - requires create-react-appto be installed globally)
  2. In your own project - under package.jsonfile remove the react-scripts
  3. Add react-scripts-tsto your project by running the command yarn add react-scripts-tsor if your are using npm then npm install react-scripts-ts. Or, add "react-scripts-ts": "2.8.0"to package.json.
  4. From the project you created in step 1 copy the files: tsconfig.json, tsconfig.test.json tslint.jsonto your own project
  5. Under your own project, in package.json, under scripts section, change react-scriptsinstances to react-scripts-ts(should be under start, build, testand eject
  6. Install the typings for react by installing the following modules using yarn or npm: @types/node, @types/reactand @types/react-dom. Put in devDependenciessection if using package.json.
  7. Change index.jsfile name to index.tsx
  8. In your tsconfig.json file add the following configuration: "allowSyntheticDefaultImports": true- for more info
  1. 通过运行命令创建一个带有 typescript 的临时 react 项目create-react-app --scripts-version=react-scripts-ts(注意 - 需要create-react-app全局安装)
  2. 在您自己的项目中 - 在package.json文件下删除react-scripts
  3. react-scripts-ts通过运行命令添加到您的项目中,yarn add react-scripts-ts或者如果您使用的是 npm then npm install react-scripts-ts. 或者,添加"react-scripts-ts": "2.8.0"到 package.json。
  4. 从您在步骤 1 中创建的项目中复制文件:tsconfig.json, tsconfig.test.json tslint.json到您自己的项目
  5. 在自己的项目中package.json,根据脚本部分,将react-scripts实例react-scripts-ts(应该是下startbuildtesteject
  6. 通过使用 yarn 或 npm 安装以下模块来安装用于 react 的类型:@types/node,@types/react@types/react-dom. devDependencies如果使用 package.json ,则放入部分。
  7. index.js文件名更改为index.tsx
  8. 在您的 tsconfig.json 文件中添加以下配置:"allowSyntheticDefaultImports": true-了解更多信息

NOTEstep 7 might require additional modification depends on what you have in your index.js file (if it depends on JS modules in the project).

注意第 7 步可能需要额外的修改,这取决于您在 index.js 文件中的内容(如果它依赖于项目中的 JS 模块)。

Now you can run your project and it might work, for those of you who are getting error that contains You may need an appropriate loader to handle this file typeregarding .js files, it happens because babel doesn't know how to load .js file from .tsx files. What we need to do is to change the project configuration. The way I found doing it without running ejectis using react-app-rewiredpackage. This package lets you configure external configuration which will be added/override the default project settings. What we'll do is using babel to load these type of files. Let's moved on:

现在你可以运行你的项目,它可能会工作,对于那些收到You may need an appropriate loader to handle this file type关于 .js 文件的错误的人来说,这是因为 babel 不知道如何从 .t​​sx 文件加载 .js 文件。我们需要做的是改变项目配置。我发现不运行的方法eject是使用react-app-rewired包。此包允许您配置将添加/覆盖默认项目设置的外部配置。我们要做的是使用 babel 来加载这些类型的文件。让我们继续:

  1. Install the package react-app-rewiredusing yarn or npm
  2. In your root folder (where package.jsonis located) create a new file with the name config-overrides.js
  3. Put this code in config-overridesfile:

    var paths = require('react-scripts-ts/config/paths')
    
    module.exports = function override(config) {
      config.module.rules.push({
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {
            babelrc: false,
            presets: [require.resolve('babel-preset-react-app')],
            cacheDirectory: true,
        },
      })
    
      return config
    }
    
  1. react-app-rewired使用 yarn 或 npm安装包
  2. 在您的根文件夹(所在package.json的位置)中创建一个名为的新文件config-overrides.js
  3. 将此代码放入config-overrides文件中:

    var paths = require('react-scripts-ts/config/paths')
    
    module.exports = function override(config) {
      config.module.rules.push({
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {
            babelrc: false,
            presets: [require.resolve('babel-preset-react-app')],
            cacheDirectory: true,
        },
      })
    
      return config
    }
    

Edit package.json so the start/start-js, build, test, and ejectscripts use react-app-rewired as shown in the project readme. E.g. "test": "react-app-rewired test --scripts-version react-scripts-ts --env=jsdom".

编辑的package.json所以start/start-jsbuildtest,和eject脚本使用反应-APP-重新接线如图所示项目自述。例如"test": "react-app-rewired test --scripts-version react-scripts-ts --env=jsdom"

Now you can start you the project and the problem should be solved. You might need additional modifications depending on your project (additional types and so).

现在你可以开始你的项目了,问题应该解决了。根据您的项目(其他类型等),您可能需要额外的修改。

Hope it helps

希望能帮助到你

As suggested here in the comments, it's possible to define: "compilerOptions": { "allowJs": true}in your tsconfig.json file, so you can mix JS and TS without react-app-rewired. Thanks for mention this!

正如评论中所建议的,可以定义:"compilerOptions": { "allowJs": true}在您的 tsconfig.json 文件中,这样您就可以在不使用 react-app-rewired 的情况下混合使用 JS 和 TS。感谢您提到这一点!

UPDATE:create-react-app version 2.1.0 support typescript so for those of you who are starting from scratch you can use it to create new application with typescript, and according to the documentationit should be done with the following command:

更新:create-react-app 2.1.0 版支持打字稿,因此对于那些从头开始的人,您可以使用它来创建带有打字稿的新应用程序,根据文档,应该使用以下命令来完成:

$ npx create-react-app my-app --typescript

For existing projects, after updating to version 2.1.0, add the following packages to your project's dependencies with the following command:

对于现有项目,在更新到 2.1.0 版本后,使用以下命令将以下包添加到项目的依赖项中:

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

and then you can simply rename .js to .ts files.

然后你可以简单地将 .js 重命名为 .ts 文件。

回答by Vincent

Create React App v2.1.0 was released today with TypeScript supporttoday. That means you no longer need to eject or use the react-scripts-tsfork; all you need to doif you have an existing Create React App project is install the required packages:

Create React App v2.1.0 今天发布,支持 TypeScript。这意味着您不再需要弹出或使用react-scripts-ts前叉;如果您有一个现有的 Create React App 项目,您需要做的就是安装所需的包:

$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
$ # or
$ yarn add typescript @types/node @types/react @types/react-dom @types/jest

You can then simply rename .jsfiles to .tsfiles to start using TypeScript.

然后,您可以简单地将.js文件重命名为.ts文件以开始使用 TypeScript。

(If you have an existing app using the create-react-app-typescript fork, here's a tutorial on how to port it to regular Create React App.)

(如果您有一个使用 create-react-app-typescript fork 的现有应用程序,这里有一个关于如何将其移植到常规 Create React App的教程。)

回答by niba

You will need to eject a configuration in order to do that.

您需要弹出配置才能执行此操作。

After ejecting you need to perform the following steps:

弹出后,您需要执行以下步骤:

  1. Add typescript extensions tsxand tsto the extensionstable in the webpack configs (dev and prod).
  2. Add ts-loader. Here is an example

    {
      test: /\.(ts|tsx)$/,
      include: paths.appSrc,
      use: [
        {
          loader: require.resolve('ts-loader'),
        },
      ],
    },
    
  3. Change eslint to tslint

  4. Add source-map-loader to get a possibility to debug Typescript files.

    {
      test: /\.js$/,
      loader: require.resolve('source-map-loader'),
      enforce: 'pre',
      include: paths.appSrc,
    }
    
  5. Create a Typescript config file and remember to set allowJsto true.

  1. 将打字稿扩展名tsx和添加tsextensionswebpack 配置(dev 和 prod)中的表中。
  2. 添加 ts-loader。这是一个例子

    {
      test: /\.(ts|tsx)$/,
      include: paths.appSrc,
      use: [
        {
          loader: require.resolve('ts-loader'),
        },
      ],
    },
    
  3. 将 eslint 改为 tslint

  4. 添加 source-map-loader 以获得调试 Typescript 文件的可能性。

    {
      test: /\.js$/,
      loader: require.resolve('source-map-loader'),
      enforce: 'pre',
      include: paths.appSrc,
    }
    
  5. 创建一个 Typescript 配置文件并记住设置allowJs为 true。