0%

常见AI提示词整理——前端开发与代码生成最佳实践

AI提示词是与AI工具进行有效沟通的关键,合适的提示词可以显著提升代码生成质量和开发效率。

介绍

  随着AI编程助手的普及,提示词工程(Prompt Engineering)已成为现代开发者的重要技能。在前端开发中,合适的AI提示词可以帮助我们快速生成高质量的代码、解决复杂的技术问题、进行代码审查和性能优化。本文将系统整理前端开发中常用的AI提示词,按功能场景分类,为开发者提供实用的参考指南。

代码生成类提示词

React组件生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 生成React函数组件

## 基础组件生成
~~~
Create a React functional component that [describe functionality].
The component should use TypeScript and follow React best practices.
Include proper TypeScript interfaces for props.
Add JSDoc comments for exported functions and components.
~~~

## 复杂组件生成
~~~
Create a [component name] component with the following requirements:
- Use React hooks (useState, useEffect, etc.)
- Include proper TypeScript types
- Follow accessibility guidelines (WCAG 2.1 AA)
- Support dark/light theme
- Include loading and error states
- Use modern React patterns (compound components, render props, etc.)

Component specification:
- [specific requirements]
- [styling framework] for styling
- [additional functionality]
~~~

## 自定义Hook生成
~~~
Create a custom React hook called use[HookName] that:
- Purpose: [describe what the hook does]
- Parameters: [describe input parameters]
- Return value: [describe return value]
- Side effects: [describe any side effects]
- Dependencies: [list external dependencies if any]

Include proper TypeScript typing and error handling.
Add comprehensive JSDoc documentation.
~~~

Vue组件生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Vue组件生成提示词

## Composition API组件
~~~
Create a Vue 3 component using Composition API that [functionality description].
Use TypeScript and follow Vue 3 best practices.

Component requirements:
- Props: [list required props with types]
- Emits: [list emitted events]
- Slots: [describe slots if needed]
- Exposed methods: [methods to expose]

Include proper TypeScript interfaces and generic typing where appropriate.
Use provide/inject for parent-child communication if needed.
~~~

## Vue组件优化
~~~
Refactor the following Vue component to improve performance and maintainability:
- Convert Options API to Composition API
- Optimize reactivity using ref/computed properly
- Add proper TypeScript typing
- Implement proper error handling
- Add loading states and error boundaries
- Follow Vue style guide recommendations
~~~

CSS/样式生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# CSS样式生成提示词

## TailwindCSS组件
~~~
Create a responsive [component name] component using TailwindCSS.
The component should:
- Be fully responsive (mobile, tablet, desktop)
- Follow accessibility best practices
- Include dark mode support
- Use Tailwind's utility classes efficiently
- Be customizable with props/config

Style requirements:
- [specific color scheme]
- [typography requirements]
- [animation/transitions if needed]
- [layout constraints]
~~~

## 动画效果生成
~~~
Create CSS animations for [describe animation purpose].
Provide both pure CSS (using @keyframes) and TailwindCSS implementations.
Include:
- Smooth transitions
- Performance optimizations (using transform, opacity)
- Responsive behavior
- Accessibility considerations (prefers-reduced-motion)
- Cross-browser compatibility notes
~~~

## 复杂布局生成
~~~
Create a complex responsive layout using CSS Grid and Flexbox that:
- Has [number] columns on desktop, [number] on tablet, [number] on mobile
- Maintains aspect ratios for images/media
- Handles content overflow gracefully
- Supports RTL languages
- Optimizes for SEO and accessibility
~~~

代码优化类提示词

性能优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 性能优化提示词

## 代码性能优化
~~~
Analyze and optimize the following code for performance:
- Identify performance bottlenecks
- Suggest React memoization strategies
- Optimize rendering with React.memo, useMemo, useCallback
- Implement code splitting and lazy loading
- Optimize bundle size
- Suggest algorithm improvements
- Identify unnecessary re-renders

Provide specific recommendations with code examples.
~~~

## 前端性能优化
~~~
Implement performance optimizations for a React application:
- Code splitting strategies
- Image optimization techniques
- Caching mechanisms
- Bundle size reduction
- Loading state optimizations
- Memory leak prevention
- Network request optimization

Provide specific implementation examples for each technique.
~~~

代码重构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 代码重构提示词

## 重构建议
~~~
Refactor the following code to improve:
- Readability and maintainability
- Performance
- Type safety (add TypeScript if missing)
- Error handling
- Testing strategy
- Separation of concerns
- Modern JavaScript/React patterns

Keep the same functionality but improve the code structure and quality.
~~~

## 从Class组件到Hook组件
~~~
Convert the following React class component to a functional component using hooks:
- Replace lifecycle methods with useEffect hooks
- Convert state management to useState/useReducer
- Handle refs appropriately
- Maintain the same functionality
- Add proper TypeScript typing
- Include proper cleanup functions
~~~

调试与问题解决

错误排查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 调试提示词

## 错误诊断
~~~
The following code is throwing [error message]. Please analyze the code and:
1. Identify the root cause of the error
2. Explain why this error occurs
3. Provide the corrected code
4. Explain the fix and why it works
5. Suggest similar errors to watch out for

Code:
[insert problematic code here]
~~~

## 性能问题诊断
~~~
The application is experiencing [performance issue description]. Please help diagnose and fix:
1. Identify potential causes
2. Suggest debugging tools to use
3. Provide code improvements
4. Recommend performance monitoring solutions
5. Estimate performance gains

Current symptoms:
- [list symptoms]
- [performance metrics if available]
- [user impact]
~~~

代码审查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 代码审查提示词

## 安全审查
~~~
Review the following code for security vulnerabilities:
- XSS prevention
- CSRF protection
- Input validation
- Sanitization practices
- Authentication/authorization issues
- Data exposure risks
- Third-party library security

Provide specific fixes for each vulnerability found.
~~~

## 质量审查
~~~
Perform a comprehensive code review focusing on:
- Code quality and readability
- Best practices adherence
- Potential bugs
- Performance considerations
- Maintainability
- Documentation completeness
- Test coverage suggestions

Rate each issue by severity and provide improvement suggestions.
~~~

国际化与多语言

I18n实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 国际化提示词

## 多语言支持
~~~
Implement internationalization (i18n) for the following React application:
- Use react-i18next or next-i18next
- Create language switcher component
- Implement RTL support where needed
- Handle pluralization
- Manage date/time formatting
- Handle number/currency formatting
- Organize translation files structure
- Implement fallback languages

Include proper TypeScript typing for translations.
~~~

## 翻译文件生成
~~~
Create translation files for [language] localization:
- Extract translatable strings from [provided code]
- Organize translations by domain/context
- Handle pluralization
- Include RTL language considerations
- Follow linguistic best practices
- Maintain consistency across translations

Provide both JSON structure and example translations.
~~~

## 日期时间国际化
~~~
Implement internationalized date and time formatting that:
- Uses user's locale automatically
- Handles different calendar systems
- Manages time zones properly
- Supports 12/24-hour formats
- Handles relative time (e.g., "2 hours ago")
- Includes proper TypeScript types

Use modern JavaScript Internationalization API.
~~~

测试相关

单元测试生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 测试生成提示词

## React组件测试
~~~
Create comprehensive unit tests for the following React component using:
- Testing Library and React Testing Library
- Jest for test runner
- TypeScript support

Test requirements:
- Render with different props
- Handle user interactions
- Test async behavior
- Mock external dependencies
- Test edge cases
- Accessibility testing
- Snapshot testing if appropriate
~~~

## API测试
~~~
Create API tests for the following endpoints:
- Test successful responses
- Test error scenarios
- Validate response schemas
- Test authentication/authorization
- Handle different HTTP methods
- Test rate limiting
- Performance testing scenarios
- Include both happy path and error cases
~~~

测试优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 测试优化提示词

## 测试重构
~~~
Refactor the following tests to improve:
- Test structure and organization
- Readability and maintainability
- Performance and speed
- Coverage and effectiveness
- Mock management
- Test data management
- Error handling in tests

Maintain test effectiveness while improving quality.
~~~

工具与配置

开发工具配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 工具配置提示词

## ESLint/Prettier配置
~~~
Create ESLint and Prettier configuration for a modern React project that:
- Enforces React best practices
- Includes TypeScript support
- Follows Airbnb or similar style guide
- Includes React Hooks rules
- Enforces import ordering
- Includes testing library rules
- Optimizes for VS Code integration
- Provides auto-fix capabilities

Provide both base configuration and React-specific extensions.
~~~

## 构建工具配置
~~~
Configure Vite for a React project with the following requirements:
- TypeScript support
- CSS preprocessing (SASS/SCSS)
- Asset optimization
- Environment variables
- Proxy configuration for API
- Code splitting setup
- Production optimization
- Development server configuration
~~~

文档与注释

代码文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 文档生成提示词

## JSDoc生成
~~~
Generate comprehensive JSDoc documentation for the following code:
- Function/method descriptions
- Parameter types and descriptions
- Return value documentation
- Exception/error documentation
- Example usage
- Accessibility considerations
- Performance implications
- Deprecation notices if applicable
~~~

## API文档
~~~
Create API documentation for the following REST endpoints:
- Request/response schemas
- Authentication requirements
- Error response formats
- Rate limiting information
- Example requests/responses
- Curl commands
- SDK usage examples
- Security considerations
~~~

AI辅助开发工作流

提示词优化策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 提示词优化策略

## 提示词结构
~~~
Effective AI prompt structure for code generation:

1. Role Definition: "Act as an experienced React/JavaScript developer"
2. Task Definition: "Create a component that..."
3. Constraints: "Use TypeScript, follow accessibility..."
4. Examples: "Similar to X, but with Y functionality"
5. Output Format: "Return code with comments and documentation"
~~~

## 上下文提供
~~~
When providing context to AI:

- Share relevant code snippets
- Explain business requirements
- Specify technical constraints
- Mention performance requirements
- Indicate design system components
- Reference existing patterns
- Clarify edge cases
- Specify testing requirements
~~~

## 反量反馈循环
~~~
Iterative improvement with AI:

1. Start with high-level requirements
2. Review initial output
3. Provide specific feedback
4. Request targeted improvements
5. Validate against requirements
6. Repeat until satisfied
~~~

常见场景专用提示词

响应式设计

1
2
3
4
5
6
7
8
9
10
11
12
13
# 响应式设计提示词

## 移动优先设计
~~~
Create a mobile-first responsive component that:
- Starts with mobile layout
- Progressively enhances for larger screens
- Uses appropriate media query breakpoints
- Maintains touch-friendly interactions
- Optimizes for mobile performance
- Considers mobile-specific UX patterns
- Follows mobile accessibility guidelines
~~~

可访问性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 可访问性提示词

## WCAG合规
~~~
Create an accessible component that complies with WCAG 2.1 AA guidelines:
- Proper heading structure
- Sufficient color contrast
- Keyboard navigation support
- Screen reader compatibility
- Focus management
- ARIA attributes where needed
- Alternative text for images
- Form accessibility
- Skip links for navigation
~~~

安全编程

1
2
3
4
5
6
7
8
9
10
11
12
13
# 安全编程提示词

## 输入验证
~~~
Implement robust input validation for [specific input type] that:
- Validates data type and format
- Implements sanitization
- Prevents injection attacks
- Handles edge cases
- Provides user-friendly error messages
- Maintains good UX while being secure
- Includes both client and server validation
~~~

实用提示词模板

通用代码生成模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 通用模板

~~~~
As an experienced [technology] developer, create [component/type] that:
PURPOSE: [what the code should accomplish]
REQUIREMENTS: [specific technical requirements]
CONSTRAINTS: [limitations or specific constraints]
TECHNOLOGY_STACK: [languages, frameworks, libraries]
PERFORMANCE: [speed, bundle size, etc. requirements]
ACCESSIBILITY: [compliance level required]
TESTING: [test coverage expectations]

Include:
- Proper TypeScript definitions if applicable
- Comprehensive error handling
- Performance optimizations
- Security best practices
- Accessibility features
- Documentation and comments
- Usage examples

Return production-ready code following industry best practices.
~~~~

调试求助模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 调试模板

~~~~
I'm experiencing [specific problem] with the following code:
[provide code snippet]

EXPECTED_BEHAVIOR: [what should happen]
ACTUAL_BEHAVIOR: [what is happening]
ERROR_MESSAGES: [any error messages]
CONTEXT: [environment, browser, dependencies]

Please help me:
1. Identify the root cause
2. Provide a solution
3. Explain why the issue occurred
4. Suggest how to prevent similar issues
5. Recommend debugging tools/techniques for similar problems

Consider [specific constraints or requirements].
~~~~

多语言翻译助手模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 多语言翻译助手

## 翻译助手角色
~~~~
Act as a professional translator. I will provide multiple texts separated by newlines. Translate each text into multiple languages and return the results in JSON format.

Languages to translate to:
- zh_CN: Simplified Chinese
- en_US: English
- ja_JP: Japanese
- ko_KR: Korean
- fr_FR: French
- de_DE: German
- es_ES: Spanish
- ar_SA: Arabic
- pt_BR: Portuguese (Brazil)
- ru_RU: Russian
- it_IT: Italian
- th_TH: Thai

Input format:
[Line 1 - text to translate]
[Line 2 - another text to translate]
[Line 3 - more text to translate]

Output format:
~~~
[
{ "lang": "zh_CN", "name": "中文", "text": "[translated text for line 1]" },
{ "lang": "en_US", "name": "英文", "text": "[translated text for line 1]" },
{ "lang": "ja_JP", "name": "日文", "text": "[translated text for line 1]" },
{ "lang": "ko_KR", "name": "韩文", "text": "[translated text for line 1]" },
{ "lang": "fr_FR", "name": "法文", "text": "[translated text for line 1]" },
{ "lang": "de_DE", "name": "德文", "text": "[translated text for line 1]" },
{ "lang": "es_ES", "name": "西班牙文", "text": "[translated text for line 1]" },
{ "lang": "ar_SA", "name": "阿拉伯文", "text": "[translated text for line 1]" },
{ "lang": "pt_BR", "name": "葡萄牙文", "text": "[translated text for line 1]" },
{ "lang": "ru_RU", "name": "俄文", "text": "[translated text for line 1]" },
{ "lang": "it_IT", "name": "意大利文", "text": "[translated text for line 1]" },
{ "lang": "th_TH", "name": "泰文", "text": "[translated text for line 1]" }
]
~~~

[Continue with translations for each input line...]

Example input:
Data Table Configuration
User Profile Management
Real-time Analytics Dashboard

Example output:
~~~
[
{ "lang": "zh_CN", "name": "中文", "text": "数据表配置" },
{ "lang": "en_US", "name": "英文", "text": "Data Table Configuration" },
{ "lang": "ja_JP", "name": "日文", "text": "データテーブル構成" },
{ "lang": "ko_KR", "name": "韩文", "text": "데이터 테이블 구성" },
{ "lang": "fr_FR", "name": "法文", "text": "Configuration du tableau de données" },
{ "lang": "de_DE", "name": "德文", "text": "Datentabellenkonfiguration" },
{ "lang": "es_ES", "name": "西班牙文", "text": "Configuración de tabla de datos" },
{ "lang": "ar_SA", "name": "阿拉伯文", "text": "تكوين جدول البيانات" },
{ "lang": "pt_BR", "name": "葡萄牙文", "text": "Configuração da tabela de dados" },
{ "lang": "ru_RU", "name": "俄文", "text": "Конфигурация таблицы данных" },
{ "lang": "it_IT", "name": "意大利文", "text": "Configurazione tabella dati" },
{ "lang": "th_TH", "name": "泰文", "text": "การกำหนดค่าตารางข้อมูล" }
]
~~~

Maintain accurate terminology and cultural appropriateness in each language.
~~~~

有效的AI提示词应该具体、清晰且包含足够的上下文信息。通过使用结构化的提示词模板,可以获得更准确、更符合需求的AI输出。

总结

  AI提示词是现代前端开发的重要工具,掌握有效的提示词技巧可以显著提升开发效率和代码质量。关键要点包括:

  1. 明确目标:清楚描述需要生成的代码功能和特性
  2. 提供上下文:包含技术栈、约束条件、性能要求等信息
  3. 结构化组织:使用清晰的结构化格式提高AI理解能力
  4. 迭代优化:根据AI输出进行调整和优化
  5. 质量检查:始终审查AI生成的代码确保质量和安全性

  随着AI技术的不断发展,提示词工程将成为前端开发者的核心技能之一。通过不断练习和优化提示词策略,开发者可以更有效地利用AI工具提升工作效率。

bulb