gal*_*van 32 javascript typescript reactjs create-react-app
几个月前我使用create-react-app启动了一个react项目,我很有兴趣将项目从Javascript迁移到Typescript.
我看到有一种方法可以使用标志创建使用typescript的react应用程序:
--scripts-version=react-scripts-ts
Run Code Online (Sandbox Code Playgroud)
但我没有找到任何解释如何将现有的JS项目迁移到TS.我需要它以递增方式完成,这样我就可以使用.js和.ts文件,这样我就可以随着时间的推移进行转换.有没有人有这种迁移的经验?为使这项工作,应该采取哪些必要步骤?
gal*_*van 54
我找到了将create-react-app从javascript迁移到typescript的解决方案,这种方式不需要弹出.
create-react-app --scripts-version=react-scripts-ts
(注意 - 需要create-react-app
全局安装)package.json
文件下删除react-scripts
react-scripts-ts
通过运行命令添加到项目中,yarn add react-scripts-ts
或者如果您正在使用npm npm install react-scripts-ts
.或者,添加"react-scripts-ts": "2.8.0"
到package.json.tsconfig.json, tsconfig.test.json tslint.json
到您自己的项目中package.json
,脚本下部分,更改react-scripts
实例react-scripts-ts
(应该是下start
,build
,test
和eject
@types/node
,@types/react
和@types/react-dom
.devDependencies
如果使用package.json,请放入部分.index.js
文件名更改为index.tsx
"allowSyntheticDefaultImports": true
- 有关详细信息注意步骤7可能需要进一步修改取决于index.js文件中的内容(如果它取决于项目中的JS模块).
现在你可以运行你的项目,它可能会工作,对于那些收到包含You may need an appropriate loader to handle this file type
.js文件的错误的人来说,它发生是因为babel不知道如何从.tsx文件加载.js文件.我们需要做的是更改项目配置.我发现不运行的方式eject
是使用react-app-rewired包.此程序包允许您配置将添加/覆盖默认项目设置的外部配置.我们要做的是使用babel加载这些类型的文件.让我们继续前进:
react-app-rewired
使用yarn或npm 安装包package.json
位置)中,使用名称创建一个新文件config-overrides.js
将此代码放入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
}
Run Code Online (Sandbox Code Playgroud)编辑的package.json所以start/start-js
,build
,test
,和eject
脚本使用反应-APP-重新接线如图所示项目自述.例如"test": "react-app-rewired test --scripts-version react-scripts-ts --env=jsdom"
.
现在你可以启动你的项目,问题应该解决.您可能需要根据项目进行其他修改(其他类型等).
希望能帮助到你
正如评论中所建议的,可以"compilerOptions": { "allowJs": true}
在你的tsconfig.json文件中定义:所以你可以混合JS和TS而不用react-app-rewired.谢谢你提一下!
更新: create-react-app版本2.1.0支持typescript,因此对于那些从头开始的人,您可以使用它来创建带有typescript的新应用程序,并且根据文档,它应该使用以下命令完成:
$ npx create-react-app my-app --typescript
Run Code Online (Sandbox Code Playgroud)
对于现有项目,在更新到2.1.0版之后,使用以下命令将以下包添加到项目的依赖项中:
$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地将.js重命名为.ts文件.
今天发布了 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
Run Code Online (Sandbox Code Playgroud)
然后,您可以简单地将.js
文件重命名为.ts
文件以开始使用TypeScript。
(如果您有一个使用create-react-app-typescript分支的现有应用程序,那么这里是有关如何将其移植到常规Create React App的教程。)
归档时间: |
|
查看次数: |
8839 次 |
最近记录: |