TypeScript项目环境配置

TypeScript简介

TypeScript 由 Microsoft 开源于 Github 上。
TypeScript 是 JavaScript 的超集,额外提供了对强类型和 ES6 的支持。
TypeScript 代码最终会编译成 JavaScript 代码来执行,进而运行在任何浏览器上。

TypeScript环境配置

ReactNative 项目中 TypeScript 的开发环境配置,参考 TypeScript官方配置

· 创建 ReactNative 工程
    react-native init MyRnDemo

· cd MyRnDemo

· 创建 src(之后的ts代码存放目录)目录
    mkdir src

· 将默认创建的 App.js 文件移动到 src 目录下
    mv App.js src

· 将 __tests__ 目录移动到 src 目录下(主要用于单元测试)
    mv ./__tests__/ ./src/__tests__/

· 测试是否可运行
    react-native run-android

· 修改 index.js 中的 App.js 的导入信息为
    import App from './lib/App';

· 添加 typescript 运行环境
    npm install --save-dev typescript

· 使用 tsc 脚本创建 typescript 编译环境
    ./node_modules/.bin/tsc --init --pretty --sourceMap --target es2015 --outDir ./lib --module commonjs --jsx react

· 添加 types 的编译环境以及 src 目录到 tsconfig.json中
    {
        "compilerOptions": {
            // other options here
            "types": ["react", "react-native"],
        },
        "include": ["./src/"]
    }

· 添加 react 库的 typescript 编译环境
    npm install --save-dev @types/react @types/react-native

· 将 src 目录中 App.js 重命名为 App.tsx,并修改 react 库的导入信息为:
    import * as React from "react";
    import {Component} from "react";

· 执行 ts->js 的代码转换监听器,并保持开启
    ./node_modules/.bin/tsc -w 

· 新开一个 Terminal 窗口运行项目
    react-native run-android

TypeScript资源推荐

猜你喜欢

转载自blog.csdn.net/pang_gua/article/details/79688862