美文网首页
react项目集成typescript

react项目集成typescript

作者: Mr无愧于心 | 来源:发表于2020-09-24 13:57 被阅读0次
一.新react项目中集成ts 脚手架搭建
  • 搭建项目

    npx create-react-app my-app --template typescript // 创建一个react-ts项目
    yarn eject // 将配置分离出来,便于后面修改相关配置
    
  • 需要增加代码校验配置

    1. 如果要使用tslint,需要在根目录增加tslint.json,然后安装相关包,并修改相关配置
    yarn add tslint tslint-config-prettier tslint-react
    

    添加tslint.json文件并配置(示例)

    // tslint.json
    {
    "extends": ["tslint-config-airbnb-base", "tslint-react"],
    "rules": {
        "ter-indent": [
            true,
            4,
            {
                "SwitchCase": 1,
                "FunctionExpression": {
                    "parameters": 1,
                    "body": 1
                }
            }
        ],
        "no-unnecessary-else": false,
        "ter-max-len": false,
        "no-empty": false,
        "no-magic-numbers": false,
        "jsx-wrap-multiline": false,
        "jsx-no-multiline-js": false,
        "jsx-no-lambda": false,
        "jsx-alignment": false,
        "jsx-no-string-ref": false,
        "variable-name": false,
        "ter-arrow-body-style": false,
        "object-literal-sort-keys": false,
        "no-console": [true, "warn", "error"],
        "comment-format": [false, "check-space"],
        "no-namespace": false,
        "interface-name": false,
        "no-shadowed-variable": false,
        "one-variable-per-declaration": false,
        "no-unused-expression": [true, "allow-fast-null-checks"],
        "radix": false,
        "only-arrow-functions": false,
        "member-ordering": false,
        "trailing-comma": false,
        "ordered-imports": false,
        "no-bitwise": false,
        "no-var-requires": false,
        "quotemark": [
            true,
            "double",
            "avoid-escape"
        ]
      }
    }
    

    在paths.js文件中增加

    appTsLint: resolveApp("tslint.json")
    

    webpack.config.js修改插件ForkTsCheckerWebpackPlugin配置,增加

    tslint: paths.appTsLint
    
  • typescript项目的路径别名不是在webpack中配置的,而是在tsconfig.json中配置的,这个别名只对ts和tsx文件有效,js文件中不能使用别名

    // tsconfig.json
     "baseUrl": ".",
     "paths": {
       "@/*": ["src/*"]
      },
    // 组件中可以用@代表src
    

    webpack.config.js添加TsconfigPathsPlugin,读取tsconfig.js中的相关数据到webpack.config.js中。

    yarn add tsconfig-paths-webpack-plugin
    
    const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
    plugins:{
      new TsconfigPathsPlugin()
    }
    
  • 使用antd按需加载

    {
          test: /\.(js|jsx|tsx|ts)$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              babelrc: true,
              plugins: [
                ['import', { libraryName: 'antd', style: 'css' }], // 按需加载
              ],
            },
          },
        },
    

    使用antd可能会有很多报错,此时应该查看antd的typescript的用法,里边包含一些antd的类型,否则会报很多错误(一定要仔细阅读antd的ts使用文档)

    // 例如Form组件
    import { Form } from 'antd';
    import { FormComponentProps } from 'antd/es/form';
    
    interface UserFormProps extends FormComponentProps {
      age: number;
      name: string;
    }
    
    class UserForm extends React.Component<UserFormProps, any> {
      // ...
    }
    
    const App = Form.create<UserFormProps>({
      // ...
    })(UserForm);
    
    //table表格
    import { Table } from 'antd';
    import { ColumnsType } from 'antd/es/table';
    
    interface User {
      key: number;
      name: string;
    }
    
    const columns: ColumnsType<User> = [
      {
        key: 'name',
        title: 'Name',
        dataIndex: 'name',
      },
    ];
    
    const data: User[] = [
      {
        key: 0,
        name: 'Jack',
      },
    ];
    
    export default () => (
      <>
        <Table<User> columns={columns} dataSource={data} />
        /* 使用 JSX 风格的 API */
        <Table<User> dataSource={data}>
          <Table.Column<User> key="name" title="Name" dataIndex="name" />
        </Table>
      </>
    );
    
二.旧react项目中集成ts
  • 安装ts所需的包
// awesome-typescript-loader
// 可以让Webpack使用TypeScript的标准配置文件tsconfig.json编译TypeScript代码,也可以用ts-loader
// source-map-loader
// 使用TypeScript输出的sourcemap文件来告诉webpack何时生成自己的sourcemaps,源码映射
yarn add typescript awesome-typescript-loader source-map-loader
// 安装声明文件 yarn add @types/库名 --save
yarn add @types/react @types/react-dom --save

  • 配置tsconfig
{
  //不带任何输入文件的情况下调用tsc,编译器会从当前目录开始去查找tsconfig.json文件,逐级向上搜索父目录。
  //当命令行上指定了输入文件时,tsconfig.json文件会被忽略。
  "compilerOptions": {// 编译的参数,"compilerOptions"可以被忽略,这时编译器会使用默认值。
    "allowJs": true, // 允许编译javascript文件。
    "checkJs":true, //在 .js文件中报告错误。与 --allowJs配合使用。
    "allowSyntheticDefaultImports": true, // 允许从没有设置默认导出的模块中默认导入。这并不影响代码的输出,仅为了类型检查。
    // "allowUnreachableCode":false, // 不报告执行不到的代码错误。
    // "allowUnusedLabels": false,// 不报告未使用的标签错误。
    // "d":false,// 生成相应的 .d.ts文件。
    // "declarationDir":'',// 生成声明文件的输出路径。
    // "diagnostics":false,// 显示诊断信息。
    // "disableSizeLimit":false,//禁用JavaScript工程体积大小的限制
    "experimentalDecorators": true,// 启用实验性的ES装饰器。
    // "extendedDiagnostics":false,// 显示详细的诊段信息。
    // "forceConsistentCasingInFileNames":false,//禁止对同一个文件的不一致的引用。
    "jsx": "react",// 在 .tsx文件里支持JSX TypeScript具有三种JSX模式:preserve,react和react-native。
    // "jsxFactory":"React.createElement",//指定生成目标为react JSX时,使用的JSX工厂函数
    "lib":[//编译过程中需要引入的库文件的列表。可能的值为:
      "es5",
      "es2015",
      "dom",
      "ES7"
    ],
    "module": "esnext", // 指定生成哪个模块系统代码  esnext 是一个 JavaScript 库,可以将 ES6 草案规范语法转成今天的 JavaScript 语法。
    "moduleResolution": "node", // 决定如何处理模块 Classic||node node的方式只能通过 ../../这种方式引入,Classic同时要引入.d.ts文件
    "target": "es5",// 指定ECMAScript目标版本
    "noImplicitReturns":false,//不是函数的所有返回路径都有返回值时报错。
    // "noImplicitUseStrict":false,//模块输出中不包含 "use strict"指令。
    // "noLib":false, // 不包含默认的库文件( lib.d.ts)
    // "noStrictGenericChecks" , // 禁用在函数类型里对泛型签名进行严格检查。
    "noUnusedLocals":true,//若有未使用的局部变量则抛错。
    "noUnusedParameters":true,//若有未使用的参数则抛错。
    // "outDir": "./dist/", // 重定向输出目录
    //"outFile":''//将输出文件合并为一个文件。合并的顺序是根据传入编译器的文件顺序和 ///<reference``>和 import的文件顺序决定的。查看输出文件顺序文件了解详情。
    // "preserveConstEnums":false, // 保留 const和 enum声明。
    "pretty":true,//给错误和消息设置样式,使用颜色和上下文。
    // "reactNamespace":"React"//当目标为生成 "react" JSX时,指定 createElement和 __spread的调用对象
    "removeComments":true,//删除所有注释,除了以 /!*开头的版权信息。
    //"skipDefaultLibCheck":false,//忽略 库的默认声明文件的类型检查。
    //"skipLibCheck":false,//忽略所有的声明文件( *.d.ts)的类型检查。
    "sourceMap": true, // 生成相应的 .map文件

    
    "strict": true,// 启用所有严格类型检查选项。启用 --strict相当于启用 --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictNullChecks和 --strictFunctionTypes和--strictPropertyInitialization。
    "noImplicitAny": false, // 在表达式和声明上有隐含的 any类型时报错。
    // "noImplicitThis":false, // 当 this表达式的值为 any类型的时候,生成一个错误。
    // "alwaysStrict": false,// 以严格模式解析并为每个源文件生成 "use strict"语句
    // "strictFunctionTypes":true,//禁用函数参数双向协变检查。
    "strictPropertyInitialization":false,//确保类的非undefined属性已经在构造函数里初始化。若要令此选项生效,需要同时启用--strictNullChecks。
    "strictNullChecks":false,//在严格的 null检查模式下, null和 undefined值不包含在任何类型里,只允许用它们自己和 any来赋值(有个例外, undefined可以赋值到 void)。
    
    // "stripInternal":false,//不对具有 /** @internal */ JSDoc注解的代码生成代码。
    //"suppressExcessPropertyErrors":false,//阻止对对象字面量的额外属性检查。
    //"suppressImplicitAnyIndexErrors":false,//阻止 --noImplicitAny对缺少索引签名的索引对象报错

    // "types":["node", "lodash", "express"],// 如果指定了types,只有被列出来的包才会被包含进来
    // "typeRoots":["./typings"],// 如果指定了typeRoots,只有typeRoots下面的包才会被包含进来。
    /* Additional Checks */
    "noFallthroughCasesInSwitch": true,//报告switch语句的fallthrough错误。(即,不允许switch的case语句贯穿)
    /* Module Resolution Options */
    "resolveJsonModule": true,// 编译选项可允许从json中导入导出其类型
    //"baseUrl": ".",//解析非相对模块名的基准目录。查看 模块解析文档了解详情。
    // "paths": {// 模块名到基于 baseUrl的路径映射的列表。
    //   "@/*": [
    //     "./src/*"
    //   ]
    // },
  },

  "include": [
    "./src/**/*", // 这个表示处理根目录的src目录下所有的.ts和.tsx文件,并不是所有文件
  ],
  "exclude": [
    "node_modules",
  ]
}
  • 配置webpack
    rules: [
        {
          test: /\.jsx?$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['react', 'env', 'stage-0', 'stage-3'],
              plugins: [
                'transform-decorators-legacy',
                ['import', { libraryName: 'antd', style: 'css' }],
              ],
            },
          },
        },
        { test: /\.tsx?$/, loader: "awesome-typescript-loader" }
        //...
      ]
    resolve: {
      extensions: [".ts", ".tsx", ".js", ".jsx"] // 引入文件可以忽略后缀
    },
    
  • 配置antd(同脚手架配置方法)

相关文章

网友评论

      本文标题:react项目集成typescript

      本文链接:https://www.haomeiwen.com/subject/xwlryktx.html