使用ts编写react应用
手动创建
-
安装 reacy 以及 react-dom
npm i react react-dom
-
安装对应声明文件
npm i -D @types/react @types/react-dom
-
修改配置项 tsconfig.ts
{ "compilerOptions": { /* Visit https://aka.ms/tsconfig.json to read more about this file */ /* Basic Options */ // "incremental": true, /* Enable incremental compilation */ "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "outDir": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ // "removeComments": true, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": false, /* Enable strict null checks. */ // "strictFunctionTypes": true, /* Enable strict checking of function types. */ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ "allowUmdGlobalAccess": true /* Allow accessing UMD globals from modules. */, /* Source Map Options */ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ /* Advanced Options */ "skipLibCheck": true /* Skip type checking of declaration files. */, "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ } }
-
在 src 目录下新建 components 文件夹
-
在 components 目录下新建 demo 文件夹
-
在 demo 目录下新建 Hello.tsx 组件
// src/cpmponents/demo/Hello.tsx import React from "react"; interface Greeting{ name: string; } const Hello = ( props: Greeting ) => <h1>Hello {props.name}</h1> export default Hello
-
将 index.ts 改为 index.tsx
// src/index.tsx import React from 'react'; import ReactDom from 'react-dom'; import Hello from './components/demo/Hello'; ReactDom.render( <Hello name="Typescript" />, document.querySelectorAll('.app')[0] )
-
修改 build / webpack.base.config.js
-
运行项目
npm start
-
优化webpack打包
因为react库体积很大,一般情况下会把库文件和业务文件拆分成两个文件,这样可以充分利用浏览器的缓存。- 修改webpack配置
// 公共环境的配置 //引入类型检查插件 // const ForkTsCheckWebpackPlugin = require('fork-ts-checker-webpack-plugin') //awesome-typescript-loader自带类型检查插件 const { CheckerPlugin } = require('awesome-typescript-loader') const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { // 指定入口文件 entry: { 'app': './src/index.tsx', }, output: { // 输出文件名,输出目录默认disk filename: '[name].[chunkhash:8].js', }, resolve: { // 指定扩展名 extensions: ['.js', '.ts', '.tsx'], }, module: { rules: [ { // 安装ts-loader : npm i ts-loader typescript -D // ts-loader正则,以ts或tsx结尾的文件 test: /\.tsx?$/i, use: [{ // loader: 'ts-loader', // 安装 npm i awesome-typescript-loader -D loader: 'awesome-typescript-loader', options:{ //安装插件做类型检查 npm i fork-ts-checker-webpack-plugin -D transpileOnly: true //只语言转换,不做类型检查 } }], // 排除 exclude: /node_modules/, }, ], }, plugins: [ // 插件,通过模板生成网站首页,把输入文件嵌入,需要安装 // npm i html-webpack-plugin -D new HtmlWebpackPlugin({ template: './src/tpl/index.html', }), // new ForkTsCheckWebpackPlugin(), // new CheckerPlugin(), ], optimization: { splitChunks: { chunks: 'all' } } };
- 修改webpack配置
-
新建终端,执行生产环境的构建
npm run build
app : 业务代码
vendors : 库代码
-
修改代码
// src/index.tsx import React from 'react'; import ReactDom from 'react-dom'; import Hello from './components/demo/Hello'; ReactDom.render( <Hello name="Typescript!!!!!!" />, document.querySelectorAll('.app')[0] )
-
重新构建
app后hash值已经改变,vendors没有改变,被浏览器缓存。 -
简单的 react 工程创建完毕。
快速创建
使用脚本+工具
-
返回到 ts_in_ation 上级目录
-
执行命令
npx create-react-app ts-react-app --typescript
- 使用 npx 可以避免全局安装,这样在装脚手架时可以下载到一个临时目录下。使用过后删除。
-
打开文件夹
-
运行
npm start
启动项目 -
目录结构
webpack等配置隐藏到了react-scripts中
使用eject命令可以暴露出一些隐藏配置(不必要且不可逆)。 -
改造工程
-
安装
npm i antd
-
安装
npm i axios
-
安装
npm i @types/react-dom
-
安装
npm i @types/react
-
安装
npm i @types/jest
-
安装
npm i @types/node
-
安装
npm i react-router-dom
-
安装
npm i typescript
-
安装
npm i @types/react-router-dom -D
-
安装
npm i npm i babel-plugin-import -D
-
安装
npm i npm i customize-cra -D
-
安装
npm i http-proxy-middleware -D
-
安装
npm i http-server -D
-
安装
npm i react-app-rewired -D
-
-
在根目录下创建文件 config.overrides.js 文件
// config.overrides.js //按需加载 const { override, fixBableImports } = require('customize-cra') module.exports = override( fixBableImports('import', { libraryName: 'antd', libraryDirextory: 'es', style: 'css' }) );
-
重新启动
npm start
-
在 src/cpmponents/demo/Hello.tsx 中引入button组件
// src/cpmponents/demo/Hello.tsx import React from "react"; import { Button } from 'antd' interface Greeting{ name: string; } const Hello = ( props: Greeting ) => <button>Hello {props.name}</button> export default Hello