本文共 4451 字,大约阅读时间需要 14 分钟。
作为独立开发者,熟悉React、Vue等前端框架并深入研究TypeScript,我希望分享一些实用的技巧和工具,使开发过程更加高效。接下来,我将详细介绍typescript在React开发中的应用,以及如何通过 Jest 进行单元测试优化,同时展示如何解决常见的路径问题和配置选项。
在React开发中,使用FunctionComponent(FC)是一种强大的选择,因为它允许我们将CSS与TSX混合,同时在外部引用并推导类型。通过使用 React.FC
,我们可以轻松地将不同类型组件化,并在中间层使用 &
来连接多个类型。
例如,一个样式化的Button组件可以定义为:
const Button: React.FC<{ disabled?: boolean; onClick?: () => void; style?: React.CSSProperties; }> = (props) => { const [disabled, setDisabled] = React.useState(false); React.useEffect(() => { if (props.disabled !== undefined) { setDisabled(props.disabled); } }, [props.disabled]); return ( );};
使用这种方式,TypeScript会自动推导出组件的类型,提供代码提示和自动修正,极大提升开发体验。
在保证代码质量方面,单元测试是不可或缺的。为了简化和优化测试流程,我推荐使用Jest,并结合以下工具和配置:
identity-obj-proxy
解决CSS模块找不到的问题。@
符号导致的路径问题。测试配置文件可以写成:
module.exports = { verbose: true, collectCoverageFrom: [ "**/*.{ts,jsx,tsx}", "!**/node_modules/**", "!**/public/**", "!**/views/**", "!**/config/**", "!**/scripts/**", "!**/src/interfaces.d.ts", ], testRegex: "./src/(.*).test.(jsx?|tsx?)$", moduleFileExtensions: ["ts", "tsx", "js", "jsx"], moduleNameMapper: { ".+.(css|less)$": "identity-obj-proxy", "^@/(.*)$": "./$1", }, transform: { "^.+\\.tsx?$": "ts-jest", "^.+\\.jsx?$": "babel-jest", "^.+\\.svg$": "jest-svg-transformer", },};
import
问题在开发过程中,常会遇到静态资源路径的问题。为了解决这一问题,可以创建一个 customs.d.ts 文件,声明如下:
declare module '*.bmp' { const src: string; export default src;}declare module '*.gif' { const src: string; export default src;}declare module '*.jpg' { const src: string; export default src;}declare module '*.jpeg' { const src: string; export default src;}declare module '*.png' { const src: string; export default src;}declare module '*.webp' { const src: string; export default src;}declare module '*.svg' { import * as React from 'react'; export const ReactComponent: React.FunctionComponent>;}declare module '*.css' { const classes: { readonly [key: string]: string; }; export default classes;}declare module '*.less' { const classes: { readonly [key: string]: string; }; export default classes;}
在 tsconfig.json
中,将 include
加入 ./custom.d.ts
,并确保 TsNode 11.3 及以上版本支持动态导入模块。
在 VSCode 中,路径问题提示可以通过修改设置来解决。安装路径IntelliSense扩展,并配置如下:
{ "emmet.includeLanguages": { "javascript": "javascriptreact", }, "pathIntellisense.mappings": { "@": "${workspaceRoot}/src", }, "typescript.suggest.paths": true}
为了确保 React JSX 转换正确,建议在 .babelrc
中配置:
{ "presets": ["@babel/preset-typescript", "@babel/preset-env"], "plugins": ["@babel/plugin-transform-react-jsx"]}
为了方便本地开发和构建,Tsconfig.json 应该包含以下内容:
{ "compilerOptions": { "jsx": "react", "module": "commonjs", "lib": ["dom", "esnext"], "checkJs": true, "allowJs": true, "target": "es5", "allowSyntheticDefaultImports": true, "strict": false, "noImplicitAny": false, "baseUrl": "./", "esModuleInterop": true, "moduleResolution": "Node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "paths": { "@/*": ["src/*"] }, "outDir": "./views" }, "include": ["./src/**/*", "./custom.d.ts"], "exclude": ["node_modules", "config", "public", "scripts"]}
为了代码质量,推荐使用ESLint。配置文件可以写成:
module.exports = { "parserOptions": { "project": "./tsconfig.json" }, "parser": "@babel/eslint-parser", "plugins": ["@babel"], "rules": { "new-cap": "warn", "no-invalid-this": "off", "no-unused-expressions": "off", "no-unused-vars": "off", "no-undef": "off", "object-curly-spacing": "off", "semi": "off" }};
为了兼容IE9及以上版本,建议在入口文件引入以下依赖:
import 'core-js/es';import 'react-app-polyfill/ie9';import 'react-app-polyfill/stable';import 'core-js/stable';import 'regenerator-runtime/runtime';import 'raf/polyfill';
确保开发工具能够兼容范围内的浏览器,配置 package.json 中的 browserslist:
{ "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all", "ie > 8" ], "development": [ "ie 11", "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }}
通过以上优化,开发过程将变得更加顺畅,同时代码质量和可读性都会得到显著提升。希望这份指南能为您的React开发之路提供有价值的参考!
转载地址:http://wiwmz.baihongyu.com/