TypeScript/JavaScript 开发指南
环境准备
前置条件
在开始 TypeScript/JavaScript 开发之前,请确保安装以下工具:
# 安装 Node.js (推荐 LTS 版本)
# 从 https://nodejs.org 下载安装
# 验证安装
node --version
npm --version
# 全局安装 TypeScript
npm install -g typescript
# 验证 TypeScript 安装
tsc --version
包管理器选择
推荐使用现代包管理器以获得更好的性能:
# 安装 pnpm (推荐)
npm install -g pnpm
# 或者使用 yarn
npm install -g yarn
# 验证安装
pnpm --version
yarn --version
推荐扩展
在 Kiro 中安装以下扩展以增强开发体验:
核心扩展
- ESLint - 代码质量检查和错误检测
- Prettier - 自动代码格式化
- Auto Rename Tag - 自动重命名 HTML/JSX 标签
- JavaScript Code Snippets - 常用代码片段
框架特定扩展
React 开发:
- ES7+ React/Redux/React-Native snippets
- React Developer Tools
- styled-components snippets
Vue.js 开发:
- Vetur (Vue 2)
- Volar (Vue 3)
- Vue VSCode Snippets
Node.js 开发:
- Node.js Modules Intellisense
- npm Intellisense
- Path Intellisense
项目配置
TypeScript 配置
使用 Kiro 创建和优化 tsconfig.json:
React TypeScript 项目配置
{
"compilerOptions": {
"target": "ES2020",
"lib": ["DOM", "DOM.Iterable", "ES6"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "src",
"paths": {
"@/*": ["*"],
"@/components/*": ["components/*"],
"@/utils/*": ["utils/*"],
"@/hooks/*": ["hooks/*"]
}
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"build"
]
}
Node.js 项目配置
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
ESLint 配置
创建 .eslintrc.js 配置文件:
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'@typescript-eslint',
'react',
'react-hooks',
],
rules: {
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/explicit-function-return-type': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'prefer-const': 'error',
'no-var': 'error',
},
settings: {
react: {
version: 'detect',
},
},
};
Prettier 配置
创建 .prettierrc 配置文件:
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}
Kiro 核心功能应用
1. 智能代码分析
代码质量检查
Kiro 可以自动分析代码并提供改进建议:
// Kiro 会建议的改进
// 原始代码
function fetchData(url: any): any {
return fetch(url).then(response => response.json());
}
// Kiro 建议的改进版本
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
性能优化建议
// Kiro 可以识别性能问题并提供优化建议
// 问题代码:不必要的重复渲染
const ExpensiveComponent = ({ items }) => {
const processedItems = items.map(item => ({
...item,
processed: heavyCalculation(item)
}));
return <div>{/* 渲染逻辑 */}</div>;
};
// Kiro 建议的优化版本
const ExpensiveComponent = ({ items }) => {
const processedItems = useMemo(
() => items.map(item => ({
...item,
processed: heavyCalculation(item)
})),
[items]
);
return <div>{/* 渲染逻辑 */}</div>;
};
2. 自动重构
转换为 async/await
// 原始 Promise 链
function getUserData(userId: string) {
return fetch(`/api/users/${userId}`)
.then(response => response.json())
.then(user => {
return fetch(`/api/users/${userId}/posts`)
.then(response => response.json())
.then(posts => ({ user, posts }));
})
.catch(error => {
console.error('Error:', error);
throw error;
});
}
// Kiro 重构后的 async/await 版本
async function getUserData(userId: string) {
try {
const userResponse = await fetch(`/api/users/${userId}`);
const user = await userResponse.json();
const postsResponse = await fetch(`/api/users/${userId}/posts`);
const posts = await postsResponse.json();
return { user, posts };
} catch (error) {
console.error('Error:', error);
throw error;
}
}
3. 调试协助
错误诊断和修复
// 常见错误:类型不匹配
interface User {
id: number;
name: string;
email: string;
}
// 错误代码
const user: User = {
id: "123", // ❌ Type 'string' is not assignable to type 'number'
name: "John",
email: "john@example.com"
};
// Kiro 建议的修复
const user: User = {
id: Number("123"), // ✅ 类型转换
name: "John",
email: "john@example.com"
};
// 或者更安全的解决方案
const createUser = (data: { id: string; name: string; email: string }): User => ({
id: parseInt(data.id, 10),
name: data.name,
email: data.email
});
编码规范和约定
Kiro Steering 文件
创建 .kiro/steering/typescript-conventions.md 定义项目约定:
# TypeScript/JavaScript 编码规范
## 命名约定
### 变量和函数
- 使用 camelCase
- 使用描述性名称
- 避免缩写
```typescript
// ✅ 推荐
const userAccountBalance = 1000;
const calculateTotalAmount = (items: Item[]) => { ... };
// ❌ 避免
const uab = 1000;
const calc = (i: any[]) => { ... };
类和组件
- 使用 PascalCase
- 组件文件名与组件名保持一致
// ✅ 推荐
class UserService { ... }
const UserProfileCard = () => { ... };
// 文件名:UserProfileCard.tsx
接口和类型
- 接口使用 PascalCase,不使用 I 前缀
- 类型别名使用 PascalCase
- 优先使用 interface 而非 type(除非需要联合类型)
// ✅ 推荐
interface UserProfile {
id: number;
name: string;
}
type Status = 'loading' | 'success' | 'error';
// ❌ 避免
interface IUserProfile { ... }
type UserProfile = { ... }; // 应该使用 interface
类型使用规范
避免 any 类型
- 使用具体类型或泛型
- 使用 unknown 替代 any(当类型确实未知时)
// ❌ 避免
function processData(data: any): any {
return data.someProperty;
}
// ✅ 推荐
function processData<T extends { someProperty: unknown }>(data: T): T['someProperty'] {
return data.someProperty;
}
### 代理钩子配置
配置自动化工作流程以保持代码质量:
#### 自动测试生成钩子
```yaml
name: "TypeScript 测试生成器"
trigger: onSave
filePattern: "src/**/*.{ts,tsx}"
instructions: |
为新的或修改的 TypeScript 函数生成对应的测试用例:
1. 分析函数的参数和返回类型
2. 生成基本的单元测试
3. 包含边界条件测试
4. 添加模拟依赖的测试
5. 确保测试覆盖主要逻辑分支
测试应该使用 Jest 和 @testing-library/react(如果是 React 组件)
类型检查钩子
name: "TypeScript 类型检查"
trigger: onSave
filePattern: "**/*.{ts,tsx}"
instructions: |
运行 TypeScript 编译器检查类型错误:
1. 执行 `tsc --noEmit` 检查类型
2. 报告所有类型错误
3. 提供修复建议
4. 检查是否有未使用的导入
依赖更新检查钩子
name: "npm 包更新检查"
trigger: manual
instructions: |
检查项目中过时的 npm 包:
1. 运行 `npm outdated` 查看过时包
2. 检查安全漏洞 `npm audit`
3. 提供安全更新建议
4. 标识破坏性更改的包
5. 生成更新计划
ESLint 自动修复钩子
name: "ESLint 自动修复"
trigger: onSave
filePattern: "**/*.{js,ts,jsx,tsx}"
instructions: |
自动修复 ESLint 错误:
1. 运行 `eslint --fix` 修复可自动修复的问题
2. 报告需要手动修复的问题
3. 确保代码符合项目规范
4. 检查格式化是否正确
MCP 服务器集成
AWS Labs Frontend MCP Server
专门为前端开发优化的 MCP 服务器,提供:
- 框架特定指导:React、Vue、Angular 最佳实践
- 性能优化建议:Bundle 分析、懒加载策略
- 构建工具配置:Webpack、Vite、Rollup 优化
- 测试策略指导:单元测试、集成测试、E2E 测试
开发工作流程
1. 项目初始化
# 创建新的 TypeScript 项目
mkdir my-typescript-project
cd my-typescript-project
# 初始化 package.json
npm init -y
# 安装 TypeScript 依赖
npm install -D typescript @types/node
# 创建 tsconfig.json
npx tsc --init
# 安装开发工具
npm install -D eslint prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin
2. 使用 Kiro 优化配置
在 Kiro 中使用以下提示来优化项目配置:
请为我的 React TypeScript 项目创建一个最佳的 tsconfig.json 配置,
包含以下要求:
- 使用 ES6 模块
- 严格类型检查
- 路径别名支持
- 适合现代浏览器的目标
3. 调试工作流
内联聊天调试
使用 Cmd/Ctrl + I 进行快速调试:
// 在有问题的代码处使用内联聊天
const result = complexFunction(data); // 选中这行,按 Cmd+I
// 询问:"这个函数可能出现什么问题?如何优化?"
添加文件到聊天
使用 Cmd/Ctrl + L 将整个文件添加到聊天:
// 将整个组件文件添加到聊天
// 询问:"请审查这个 React 组件,提供性能和可维护性建议"
4. 文档访问
使用 Kiro 的内置文档引用系统:
// 在聊天中使用 #docs 引用
// "如何使用 #docs:react 的 useEffect 钩子?"
// "请查看 #docs:typescript 中关于泛型的说明"
测试策略
单元测试配置
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
'!src/**/*.test.ts',
],
coverageThreshold: {
global: {
branches: 70,
functions: 70,
lines: 70,
statements: 70,
},
},
};
React 测试配置
// setupTests.ts
import '@testing-library/jest-dom';
// 示例组件测试
import { render, screen, fireEvent } from '@testing-library/react';
import { UserCard } from './UserCard';
describe('UserCard', () => {
const mockUser = {
id: 1,
name: 'John Doe',
email: 'john@example.com',
};
it('should render user information', () => {
render(<UserCard user={mockUser} />);
expect(screen.getByText('John Doe')).toBeInTheDocument();
expect(screen.getByText('john@example.com')).toBeInTheDocument();
});
it('should handle click events', () => {
const onClickMock = jest.fn();
render(<UserCard user={mockUser} onClick={onClickMock} />);
fireEvent.click(screen.getByRole('button'));
expect(onClickMock).toHaveBeenCalledWith(mockUser);
});
});
性能优化
Bundle 分析
// webpack-bundle-analyzer 配置
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
],
};
代码分割
// 路由级别的代码分割
import { lazy, Suspense } from 'react';
const HomePage = lazy(() => import('./pages/HomePage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Suspense>
);
}
组件级优化
// 使用 React.memo 优化重新渲染
import { memo } from 'react';
interface Props {
items: Item[];
onItemClick: (item: Item) => void;
}
export const ItemList = memo<Props>(({ items, onItemClick }) => {
return (
<ul>
{items.map(item => (
<li key={item.id} onClick={() => onItemClick(item)}>
{item.name}
</li>
))}
</ul>
);
});
推荐资源
官方文档
框架特定资源
React 生态:
- React 官方文档
- React TypeScript Cheatsheet
- Testing Library 文档
Vue.js 生态:
- Vue 3 官方文档
- Vue TypeScript 支持
- Pinia 状态管理
Node.js 生态:
- Express.js 文档
- NestJS 文档
- Fastify 文档
工具和库
- 构建工具:Vite、Webpack、Rollup
- 测试框架:Jest、Vitest、Playwright
- 代码质量:ESLint、Prettier、Husky
- 类型工具:utility-types、type-fest
页面最后更新:2025年7月21日