Stop Telling AI to 'Write a Component' — Build a Frontend Prompt Library That Ships Code
Frontend Prompt Engineering in Practice: How to Build a Scenario-Based Prompt Library
1. What Problem Does This Chapter Solve?
The most common problem when using AI in frontend development is not that "AI can't write code," but that the tasks you give it are too vague.
For example, a sentence like:
Write me a user list page
The AI is very likely to give you code that looks complete but is actually difficult to integrate into a project. It doesn't know your tech stack, API structure, component conventions, or how your team handles loading, error states, permissions, and testing.
A better approach is to distill common tasks into reusable Prompt templates. The purpose of a template is not to make a sentence longer, but to ensure the AI always receives sufficient context, constraints, and acceptance criteria.
After reading this chapter, you should be able to do three things:
- Design reusable Prompts for high-frequency frontend scenarios.
- Judge whether a Prompt's output can be integrated into a project.
- Clearly explain in an interview how you use AI to improve frontend development efficiency.
2. The Core of Prompt Engineering: Turning Requirements into Executable Instructions
Prompt engineering can be simply understood as: using structured language to tell the AI the task goal, context, constraints, and output format.
In frontend scenarios, a good Prompt typically contains six parts:
Role: The identity you want the AI to answer as
Background: Project tech stack, business scenario, existing constraints
Task: What specifically needs to be accomplished this time
Input: APIs, fields, component requirements, error messages, or report content
Constraints: Code standards, boundary conditions, prohibitions
Output: The format in which you want the AI to deliver
It can be remembered as a formula:
Good Prompt = Role + Background + Input + Constraints + Output Format + Acceptance Criteria
The most easily overlooked part is "Acceptance Criteria." If you only say "write it a bit better," the AI is hard-pressed to execute stably; if you say "must include loading, empty, and error states, and provide basic test cases," the output becomes much more controllable.
3. How to Judge if a Prompt is Qualified
Before writing a template, you can use the following checklist to judge quality.
| Check Item | Unqualified Writing | Better Writing |
|---|---|---|
| Task Goal | Write me a component | Generate a React UserCard component for displaying avatar, name, department, and title |
| Technical Context | Use frontend | React 18 + TypeScript + Ant Design 5 + CSS Modules |
| Input Information | As usual | Provide Props, API fields, event callbacks, and default values |
| Output Format | Give me the code | Output index.tsx, types.ts, styles.module.css, and test files according to the file structure |
| Quality Constraints | Code should be a bit standardized | Must handle loading, empty, error states; complete Props type definitions |
| Acceptance Criteria | Just make it work | After generation, must pass TypeScript checks and cover 3 core interaction tests |
A truly reusable Prompt is not one that produces a good-looking result once, but one that can output stably even when given a similar but different requirement.
4. Scenario 1: Standardizing Component Development
1. Applicable Scenarios
When a team frequently develops business components like lists, forms, modals, and detail cards, it is most suitable to distill a component generation Prompt.
The focus of this type of Prompt is not "making the AI write a lot of code," but making it adhere to the project structure and team conventions.
2. React Business Component Prompt Template
You are a senior frontend engineer. Please generate a React business component based on the following information.
【Project Tech Stack】
- React 18
- TypeScript
- Ant Design 5
- CSS Modules
- Testing Framework: Vitest + React Testing Library
【Component Information】
Component Name: {ComponentName}
Business Purpose: {Explain what business problem this component solves}
Usage Page: {Which page or module it is used in}
【Props Definition】
- {propName}: {type} - {description} - {required/optional} - {default value}
【Interaction Behavior】
1. {Interaction behavior one}
2. {Interaction behavior two}
3. {Interaction behavior three}
【State Requirements】
- loading: {How to display when loading}
- empty: {How to display when there is no data}
- error: {How to display when an exception occurs}
【Code Standards】
1. Props must have complete TypeScript type definitions.
2. The component should not directly request APIs; data is passed in via Props.
3. Styles are written in styles.module.css.
4. Event callbacks are named using the onXxx convention.
5. Do not introduce unrelated dependencies.
【Output Requirements】
Please output according to the following file structure:
ComponentName/
├── index.tsx
├── types.ts
├── styles.module.css
└── ComponentName.test.tsx
Output each file separately in a code block.
Finally, add an "Acceptance Checklist" explaining which requirements the generated code meets.
3. Usage Example
You are a senior frontend engineer. Please generate a React business component based on the following information.
【Project Tech Stack】
- React 18
- TypeScript
- Ant Design 5
- CSS Modules
- Testing Framework: Vitest + React Testing Library
【Component Information】
Component Name: UserCard
Business Purpose: Display basic user information, support clicking to enter user details
Usage Page: Backend user management list
【Props Definition】
- userId: string - User ID - Required
- name: string - User Name - Required
- avatarUrl?: string - User Avatar - Optional - Default display placeholder avatar
- department?: string - Department - Optional
- title?: string - Job Title - Optional
- loading?: boolean - Whether loading - Optional - Default false
- onCardClick?: (userId: string) => void - Card click callback - Optional
【Interaction Behavior】
1. When the card is clicked, if onCardClick is provided, call onCardClick(userId).
2. When loading is true, display a skeleton screen and do not trigger click events.
3. When avatarUrl is empty, display a default avatar.
【State Requirements】
- loading: Display Skeleton
- empty: Display "Unknown User" when name is empty
- error: This component does not handle API errors; fallback data is passed in by the parent component
【Code Standards】
1. Props must have complete TypeScript type definitions.
2. The component should not directly request APIs; data is passed in via Props.
3. Styles are written in styles.module.css.
4. Event callbacks are named using the onXxx convention.
5. Do not introduce unrelated dependencies.
【Output Requirements】
Please output according to the following file structure:
UserCard/
├── index.tsx
├── types.ts
├── styles.module.css
└── UserCard.test.tsx
Output each file separately in a code block.
Finally, add an "Acceptance Checklist" explaining which requirements the generated code meets.
4. Why This Template is Effective
It clarifies upfront the points most prone to errors in component development: where data comes from, how states are displayed, how events are named, how files are organized, and what tests cover.
Be careful not to cram all project conventions in. A component-level Prompt only needs to include rules strongly related to the current component generation. For example, code commit conventions, route permission design, and API retry strategies should not be placed in this Prompt.
5. Scenario 2: Performance Optimization Analysis
1. Applicable Scenarios
Performance optimization tasks are suitable for letting AI do "analysis and solution breakdown," but not suitable for just saying "help me optimize performance."
You need to provide real input, such as Lighthouse reports, Bundle analysis results, resource sizes, first screen load time, and page structure. Without this input, the AI can only give generic advice.
2. Lighthouse Report Analysis Prompt
You are a frontend performance optimization expert. Please analyze the following Lighthouse report and provide an executable optimization plan.
【Project Background】
- Framework: {React/Vue/Next.js/Nuxt}
- Build Tool: {Webpack/Vite/Rollup}
- Deployment Method: {Nginx/CDN/Vercel/Other}
- Page Type: {Official Site/Backend Admin/Mobile H5/E-commerce Detail Page}
【Lighthouse Scores】
- Performance: {score}
- Accessibility: {score}
- Best Practices: {score}
- SEO: {score}
【Main Issues】
{Paste Lighthouse Opportunities and Diagnostics content}
【Constraints】
- Do not change the existing tech stack.
- Prioritize optimizations that can be completed within 1 day.
- When code changes are involved, provide example code or configuration.
- Do not just explain theory.
【Output Format】
Please output according to the following structure:
## Priority Ranking
Use a table to list issues, impact, priority, and estimated benefit.
## Quick Optimization Items
List modifications that can be completed within 1 day, providing specific code or configuration.
## Medium-to-Long Term Optimization Items
List optimizations that require refactoring or cross-team collaboration.
## Verification Method
Explain how to re-test after optimization.
3. Bundle Analysis Prompt
You are a frontend build optimization expert. Please analyze the bundle size based on the following information and provide a code splitting plan.
【Current Situation】
- Build Tool: {Webpack/Vite/Rollup}
- Main Bundle Size: {xxx KB/MB}
- Number of Routes: {number}
- Largest Dependencies: {List dependencies with large sizes}
- SSR or not: {Yes/No}
【Bundle Analysis Results】
{Paste main information from webpack-bundle-analyzer or rollup-plugin-visualizer}
【Business Constraints】
- Modules that must be loaded on the first screen: {List}
- Modules that can be lazy-loaded: {List}
- Dependencies that cannot be changed: {List}
【Output Requirements】
1. Identify modules that can be lazy-loaded.
2. Provide a route-level code splitting plan.
3. Provide a plan for on-demand importing of third-party libraries.
4. Explain the risks of each optimization.
5. Provide a verification method after optimization.
4. The Key to Performance Prompts
Performance optimization cannot just ask "how to optimize"; you must let the AI judge priorities based on evidence.
A high-quality performance Prompt must at least include:
- Current metrics.
- Specific reports.
- Page type.
- Business constraints.
- Verification method.
Otherwise, the AI can easily give generic advice like "enable caching, compress images, lazy load" which is correct but not useful enough.
6. Scenario 3: Improving Team Collaboration Efficiency
1. Applicable Scenarios
Team collaboration Prompts are suitable for distilling repetitive tasks that require quality expression, such as Commit Messages, PR descriptions, technical documentation, and Code Review summaries.
The focus of these tasks is to unify formats and reduce communication costs.
2. Commit Message Generation Prompt
Please generate a Git Commit Message that conforms to team conventions based on the following changes.
【Commit Convention】
Format: <type>(<scope>): <subject>
type options:
- feat: New feature
- fix: Bug fix
- docs: Documentation changes
- style: Formatting adjustments, no logic impact
- refactor: Refactoring
- perf: Performance optimization
- test: Test related
- chore: Build process or dependency adjustments
【Changes This Time】
{Describe what was changed. If you have a git diff, you can paste the key diff.}
【Requirements】
1. subject should be in Chinese.
2. subject should not exceed 50 characters.
3. Clearly state what was changed, avoid vague descriptions like "optimize code."
4. If it's a fix, explain what problem was fixed.
Please output 3 alternative Commit Messages and explain which one is recommended.
3. PR Description Generation Prompt
Please generate a Pull Request description based on the following information.
【Change Background】
{Why this PR is needed}
【Change Content】
{List the main changes}
【Scope of Impact】
{Pages, components, APIs, or configurations involved}
【Testing Status】
- Unit Tests: {Passed/Not Executed/Not Applicable}
- Manual Testing: {List test scenarios}
- Regression Risk: {Explain potentially affected areas}
【Output Format】
Please output according to the following structure:
## Change Description
## Change Type
- [ ] New Feature
- [ ] Bug Fix
- [ ] Refactoring
- [ ] Performance Optimization
- [ ] Documentation Update
## Testing Status
## Review Focus
## Screenshots or Recordings
If it's a UI change, remind me to add screenshots or recordings.
Requirements: Content should be specific, avoid boilerplate, allowing reviewers to quickly judge whether this PR needs focused attention.
4. Technical Documentation Prompt
You are a frontend technical documentation author. Please help me write a technical document.
【Document Type】
{Functional Design Document / API Specification / Component Usage Document / Project Architecture Description}
【Target Audience】
{Frontend Newcomers / Backend Colleagues / Testing Colleagues / Product Managers}
【Background Information】
- Project Name: {Project Name}
- Involved Modules: {Module Name}
- Tech Stack: {Tech Stack}
- Current Problem: {Why this document is needed}
【Core Content】
{Roughly list the content to be written using bullet points}
【Output Requirements】
1. Use Markdown.
2. Write the background first, then the solution.
3. Use Mermaid when involving processes.
4. Use tables when involving fields.
5. Finally, provide notes and FAQ.
Please write a version that can be directly placed into the team's document library.
7. Prompt Optimization Methods: From "Usable" to "Stably Reusable"
1. Decompose Complex Tasks
For complex tasks, do not let the AI go from requirements to code in one go.
Not recommended:
Help me make a user management page.
More recommended:
I want to make a user management page. Please first complete only the first step: Design the page data structure and API call plan.
【Page Features】
- User list
- Search and filter
- Add user
- Edit user
- Delete user
【Tech Stack】
- React 18
- TypeScript
- Ant Design 5
- Zustand
【Output Requirements】
1. List the required APIs.
2. Design the frontend state structure.
3. Explain what each component is responsible for.
4. Do not write specific UI code for now.
First let the AI do the design, then let it write the components, and finally let it supplement tests. The more complex the task, the more it needs to be broken down into verifiable small steps.
2. Provide Positive and Negative Examples
If you want the AI to output in a certain style, giving examples directly is more effective than abstract descriptions.
Please help me write form validation functions, error messages should be specific.
【Good Example】
if (!email.includes('@')) {
return { valid: false, message: 'Email format is incorrect, missing @ symbol' };
}
【Bad Example】
if (!validate(email)) {
return { valid: false, message: 'Input error' };
}
Please generate validation functions for phone numbers and ID numbers following the style of the good example.
"Specific" itself is not specific enough. Write out what you want the output to look like, and the AI will be more likely to replicate it.
3. Clarify Output Format
When the AI's output needs to go into documents, scripts, or systems, the format must be explicit.
Please organize the following API fields.
【Input】
{Paste API fields}
【Output Format】
Only output a Markdown table with the following fields:
| Field Name | Type | Required | Default Value | Description |
| --- | --- | --- | --- | --- |
Do not output any explanation outside the table.
The core of this type of Prompt is to reduce post-processing costs. The more explicit you are, the easier the AI's output is to reuse directly.
4. Add an Acceptance Checklist
Many people write Prompts with only generation requirements, not acceptance requirements. It is recommended to fix a segment at the end of the template:
After completing the output, please supplement an acceptance checklist, explaining item by item:
1. Whether it meets the tech stack requirements.
2. Whether it covers loading, empty, and error states.
3. Whether it has complete TypeScript types.
4. What assumptions you have made.
5. Which parts need to be adjusted according to the actual project situation.
The benefit of doing this is that the AI will proactively expose assumptions and risks, making it easier for you to review.
8. How to Build a Team Prompt Library
A Prompt library should not just be a "collection of favorite common phrases," but should be managed like a code snippet library.
1. Recommended Directory Structure
prompts/
├── component/
│ ├── react-component.md
│ ├── vue-component.md
│ └── component-doc.md
├── performance/
│ ├── lighthouse-analysis.md
│ ├── bundle-splitting.md
│ └── image-optimization.md
├── collaboration/
│ ├── commit-message.md
│ ├── pr-description.md
│ └── tech-doc.md
└── README.md
Each Prompt file is recommended to contain:
- Applicable scenarios.
- Input field descriptions.
- Prompt template.
- Usage example.
- Output acceptance criteria.
- Version history.
2. Version Management
Prompts also need iteration. It is recommended to record the reason for each modification.
## Version History
### v1.0
- Initial version, supports basic React component generation.
### v1.1
- Added loading, empty, error state requirements.
- Added test file output requirement.
### v1.2
- Removed overly heavy JSDoc requirements to avoid generating redundant comments.
- Added constraint "component should not directly request APIs."
Version history is not formalism. It helps the team know: why this Prompt became what it is now, and what problems it has solved.
3. Iteration Process
It is recommended to maintain Prompts according to this process:
- Record Problem: Where the AI output does not meet project requirements.
- Modify Template: Supplement missing context or constraints.
- Regenerate: Use the same case to verify if the result has improved.
- Code Review: Confirm whether the generated content can enter the project.
- Update Version: Record the reason for the change.
Don't directly deny AI just because a certain output was bad. First judge whether it's a model capability issue or the Prompt lacks context.
9. How to Express This Kind of Experience in an Interview
If an interviewer asks: "How do you usually use AI to improve frontend development efficiency?"
Don't just answer:
I use AI to write code, generate documentation, and optimize performance.
This answer is too vague and doesn't reveal your engineering judgment.
You can answer like this:
I don't directly let AI write complete business code. Instead, I break down high-frequency frontend tasks into several controllable scenarios, such as component generation, performance analysis, PR descriptions, and technical documentation.
For component generation, I explicitly state the tech stack, Props, state requirements, file structure, and testing requirements in the Prompt to avoid AI generating code that cannot be integrated into the project.
For performance optimization, I use Lighthouse or Bundle analysis results as input, letting the AI sort by impact scope and implementation cost, rather than just giving generic advice.
At the team level, I distill these high-frequency Prompts into a template library, continuously iterating with version history and acceptance checklists. This way, AI is not just a personal efficiency tool, but part of the team's conventions.
This answer reflects three points:
- You know what AI is suitable for and also know its boundaries.
- You can integrate Prompt engineering into the actual frontend workflow.
- You have a sense of team collaboration and quality control.
If you want to add extra points, you can add one more sentence:
I treat AI-generated results as a first draft, not the final answer. Areas involving business logic, permissions, security, and performance still require manual review and test verification.
This sentence reflects maturity. AI efficiency is not about skipping the engineering process, but about automating repetitive labor upfront, leaving human energy for judgment and verification.
10. Practical Exercises
Exercise 1: Write a Component Generation Prompt
Choose the most common component type in your project, such as a form, list, modal, or detail card.
Requirements:
- Clearly write the tech stack.
- Clearly write the Props.
- Clearly write the loading, empty, error states.
- Clearly write the output file structure.
- Let the AI generate test cases.
Verification Method:
- Can the generated code pass TypeScript checks?
- Does it require a lot of manual modification?
- Does it conform to team naming and directory conventions?
Exercise 2: Optimize an Old Prompt
Find a Prompt you used before but with unstable results, and review it according to the following format:
| Item | Description |
|---|---|
| Original Prompt | How you wrote it at the time |
| Problem | Where the AI output did not meet expectations |
| Missing Information | Was it missing tech stack, input, constraints, or output format? |
| Optimized Version | How the new Prompt was changed |
| Verification Result | Did the output become more stable? |
Exercise 3: Build a Small Team Prompt Library
Don't aim for completeness at first; it is recommended to start with 5 templates:
- React/Vue component generation.
- Component documentation generation.
- Lighthouse report analysis.
- Commit Message generation.
- PR description generation.
Each template must have "Applicable Scenarios" and "Acceptance Checklist." Without these two items, Prompts easily become long texts that are just copied and pasted.
11. Frequently Asked Questions
Q1: Is a more detailed Prompt always better?
No.
The goal of a Prompt is to provide necessary context, not to cram all team conventions in. An overly long Prompt dilutes focus and can make the AI waver between multiple objectives.
A good practice is: provide only what the current task needs. A component generation Prompt should not mix in deployment specifications, and a performance analysis Prompt should not mix in Commit conventions.
Q2: Why does the same Prompt produce different outputs each time?
Because large models inherently have generation randomness, and different models adhere to constraints to varying degrees.
If you want more stable output, you can:
- Clarify the output format.
- Provide positive and negative examples.
- Use strong constraint words like "must" and "prohibit."
- Break complex tasks into multiple rounds.
- Add an acceptance checklist for key outputs.
Q3: Does a Prompt library need maintenance?
Yes.
Whenever the project tech stack, code conventions, or component structure changes, the Prompts should be updated synchronously. Otherwise, the AI-generated content will gradually become disconnected from the real project.
Q4: How can a team avoid everyone writing their own set of Prompts?
Prompts can be placed in the team's documentation or code repository, and reverse-distilled during Code Review.
If everyone finds that a certain type of code frequently needs repeated modification, it indicates that the Prompt template needs updating. A Prompt library is not a one-time product, but a tool that evolves alongside the team's practices.
12. Chapter Summary
The value of frontend Prompt engineering is not to let AI complete all development for you, but to standardize high-frequency, repetitive, rule-clear tasks.
A qualified scenario-based Prompt must at least include:
- A clear task goal.
- Necessary project context.
- Executable input information.
- Clear quality constraints.
- A fixed output format.
- Checkable acceptance criteria.
When you can distill scenarios like component development, performance optimization, and team collaboration into a template library, AI truly transforms from a "temporary chat tool" into an "engineering efficiency tool."
For interviews, the focus is also not on memorizing a few Prompt techniques, but on clearly explaining: how you integrate AI into the real frontend workflow, how you control output quality, and how you distill personal experience into team assets.