【前端】一些让你事半功倍的 ChatGPT Prompts 建议~

ChatGPT 的横空出世,开启了人工智能的一个新纪元。不可否认的是,像 ChatGPT 和 Copilot 这样的人工智能工具已经彻底改变了我们的写代码方式。它们不仅节省了时间,实际上还让整个开发者体验(DX)更好。要充分利用这一强大工具,了解如何编写有效的提示至关重要。

下面总结一些我自己学到的高效使用 ChatGPT 的建议和模板,需要的时候直接替换其中的关键部分即可获得相对准确的回复 ~

Prompt 建议

1. 清晰明确

  • ❌ "How do I center something?" (我怎么实现居中?)
  • ✅ "What's the best way to center a div element horizontally and vertically on a webpage?" (在网页上将 div 元素水平居中和垂直居中的最佳方法是什么?)

在编写提示时,请尽可能清晰和具体。这有助于 ChatGPT 充分理解你的需求,并提供相关信息或代码示例。

2. 明确语言和上下文

  • ❌ "Explain reduce" (解释一下reduce)
  • ✅ "Explain JavaScript's reduce() method, and include two simple code examples." (解释 JavaScript 的 reduce() 方法,并给出两个简单的代码示例。)

Try to provide context by specifying the programming language or technology you're working with. Also, consider your expertise level and project status to tailor the response effectively.

3. 化整为零

  • ✅ "Explain JavaScript's reduce() method to me as if I am a beginning developer just learning how to code. Provide an example of how I can use reduce() to calculate the total price of several items in a shopping cart."
  • 向我解释 JavaScript 的 reduce() 方法,就像我是一个刚刚学习如何编写代码的初级开发人员一样。举例说明如何使用 reduce() 计算购物车中几件商品的总价。

延伸到提示二,将复杂的问题分解成更小的、可操作的步骤。这样,ChatGPT 就更容易提供全面的答案。

4. 提供需求示例

  • ❌ "How do I create a form?" (我怎么创造一个表单 )
  • ✅ "Your task is to create a form in JavaScript with one input that accepts a string and prints that string to the webpage in reverse on submit."(你的任务是用 JavaScript 创建一个表单,该表单有一个输入,接受一个字符串,并在提交时将该字符串反向打印到网页上。)

提供需求示例有助于 ChatGPT 准确理解你想要实现的目标,并生成更准确的响应。

5. 提供需求细节

  • ❌ "Show me an example React component" (给我写个react组件demo)
  • ✅ "Create an example of React component that takes in at least one prop and demonstrates how to use hooks like useState and useEffect. The example should not be a typical 'Hello World' example like a counter or a greeting. Assume that I have already set up a React project."(创建一个 React 组件示例,其中至少包含一个道具,并演示如何使用使用状态(useState)和使用效果(useEffect)等钩子。该示例不应是典型的 "Hello World "示例,如计数器或问候语。假设我已经建立了一个 React 项目。)

提供具体细节和项目状态将有助于你获得符合需求的答案。请明确提出你的要求,以避免得到笼统的答复。

6. 描述输出形式

  • ✅ Ask for steps: "Provide a brief 2-step explanation of creating a custom JavaScript event"
  • ✅ 要求步骤:"简要说明创建自定义 JavaScript 事件的 2 个步骤"
  • ✅ Table: "Highlight the differences between React and Vue in a tabular format"
  • ✅ 表格:"以表格形式强调 React 和 Vue 之间的差异"
  • ✅ Summarize with bullet points: "Please summarize in 3 bullet points why innerHTML should be avoided"
  • ✅ 用要点进行总结:"请用 3 个要点总结为何应避免使用 innerHTML"
  • ✅ Summarize as flow chart: "Use a flowchart to explain how to make a pull request on Github"
  • ✅ 以流程图的形式总结:"使用流程图解释如何在 Github 上提交拉取请求"
  • ✅ Summarize as pseudo code: "Create pseudo code in the form of code comments describing how I can write a React component that displays the time in a user's local timezone."
  • ✅ 总结为伪代码:"以代码注释的形式创建伪代码,描述我如何编写一个 React 组件,以显示用户所在时区的时间。"

我们可以通过指定你的偏好来控制回复的长度和格式。你可以根据自己的要求要求简洁的答案、详细的解释或代码片段。

7. 基于角色的 Prompting

  • ✅ "Act as a product owner to help me define crucial features for my app and write user stories."
  • ✅"作为一个产品负责人,帮助我定义应用程序的关键功能并编写用户故事"。
  • ✅ "Act as a software architect and help me determine which technologies to use for my web app."
  • ✅"作为一个软件架构师,帮我确定网络应用程序应使用哪些技术"。
  • ✅ "Act as a senior engineer and advise me on best practices."
  • ✅ "作为一个高级工程师,为我提供最佳实践方面的建议。"

无论是项目规划、技术决策还是编码指导,ChatGPT 都能扮演不同的角色,为你提供有效的帮助。

8. 提供代码示例

✅ "Please write a function to total an array of numbers and return the value as a dollar amount(请编写一个函数,对数字数组进行合计,并以美元金额返回值:):

Example input(输入示例): [5, 40.5, 9, 45, 23, 50]

Example output(输出示例): "$172.50"

提供输入和输出结果的具体示例将有助于 ChatGPT 针对你的请求提供精确的代码解决方案。

Prompt 模板

UI 生成

Generate a semantic and accessible HTML and (framework) CSS [UI component] consisting of [component parts]. The [component parts] should be [layout].


Example:

  • 英文版:Generate a semantic HTML and Tailwind CSS "Contact us" form consisting of the user's name, email, issue type, and message. The form elements should be stacked vertically and placed inside a card.
  • 中文版:生成包含用户姓名、电子邮件、问题类型和信息的语义 HTML 和 包含 Tailwind CSS 央视的 "联系我们" 表单。表单元素垂直堆叠并放置在卡片内。

函数/方法

Write a JavaScript function. It accepts [input] and returns [output].


Example:

  • 英文版:Write a JavaScript function. It accepts a full name as input and returns avatar letters.
  • 中文版:编写一个 JavaScript 函数。它接受全名作为输入,并返回头像字母。
js 复制代码
function getAvatarLetter(fullName) {
  // 处理输入为空或非字符串的情况
  if (!fullName || typeof fullName !== 'string') {
    return '';
  }

  // 将全名分割成单词
  const words = fullName.split(' ');

  // 获取头像字母
  let avatarLetter = '';

  // 如果有多个单词,则取第一个单词和最后一个单词的首字母
  if (words.length > 1) {
    avatarLetter = words[0][0] + words[words.length - 1][0];
  }
  // 如果只有一个单词,则取单词的前两个字母
  else if (words.length === 1) {
    avatarLetter = words[0].slice(0, 2);
  }

  // 将头像字母转换为大写并返回
  return avatarLetter.toUpperCase();
}

// 示例用法
const fullName = 'John Doe';
const avatarLetter = getAvatarLetter(fullName);
console.log(`Avatar Letter: ${avatarLetter}`); // JD

服务端代码

Write a/ an [framework] API for [functionality]. It should make use of [database].


Example:

  • 英文版:Write an Express.js API to fetch the current user's profile information. It should make use of MongoDB.
  • 中文版:编写一个 Express.js API 来获取当前用户的个人资料信息。它应使用 MongoDB。
js 复制代码
// Install required packages
// npm install express mongoose

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = 3000;

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;

// Define user schema
const userSchema = new mongoose.Schema({
  username: String,
  email: String,
  // Add other fields as needed for the user's profile
});

// Create user model
const User = mongoose.model('User', userSchema);

// Example middleware to simulate authentication
const authenticateUser = (req, res, next) => {
  // In a real application, you would perform user authentication here
  // For simplicity, we'll assume the user is already authenticated
  req.userId = 'yourUserId'; // Replace with your authentication logic
  next();
};

// Express route to fetch current user's profile
app.get('/api/profile', authenticateUser, async (req, res) => {
  try {
    // Assuming you have a User model with an "_id" field
    const currentUser = await User.findById(req.userId);

    if (!currentUser) {
      return res.status(404).json({ message: 'User not found' });
    }

    // Return user profile information
    res.json({
      username: currentUser.username,
      email: currentUser.email,
      // Add other fields as needed
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// Start the Express server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

SQL

The database has [comma-separated table names]. Write a [database] query to fetch [requirement].


Example:

  • 英文版:The database has students and course tables. Write a PostgreSQL query to fetch a list of students who are enrolled in at least 3 courses.
  • 中文版:数据库中有学生表和课程表。编写 PostgreSQL 查询,获取至少注册了 3 门课程的学生列表。
sql 复制代码
SELECT s.student_id, s.student_name
FROM students s
JOIN (
  SELECT student_id, COUNT(course_id) AS course_count
  FROM registrations
  GROUP BY student_id
  HAVING COUNT(course_id) >= 3
) r ON s.student_id = r.student_id;

代码补全

Complete the code [code snippet]


Example: Complete the code(完成下列代码):

js 复制代码
const animals = ["dogs", "cats", "birds", "fish"];
let animal = animals[Math.floor(Math.random() * animals.length)];

switch (animal) {
  case "dogs":
    console.log(
      "Dogs are wonderful companions that bring joy and loyalty into our lives. > Their wagging tails and wet noses never fail to make us smile."
    );
    break;
}

参考资源

相关推荐
Redstone Monstrosity5 分钟前
字节二面
前端·面试
东方翱翔12 分钟前
CSS的三种基本选择器
前端·css
Fan_web35 分钟前
JavaScript高级——闭包应用-自定义js模块
开发语言·前端·javascript·css·html
营赢盈英42 分钟前
Azure OpenAI and token limit
ai·chatgpt·asp.net·azure·openai api
yanglamei196243 分钟前
基于GIKT深度知识追踪模型的习题推荐系统源代码+数据库+使用说明,后端采用flask,前端采用vue
前端·数据库·flask
千穹凌帝43 分钟前
SpinalHDL之结构(二)
开发语言·前端·fpga开发
dot.Net安全矩阵1 小时前
.NET内网实战:通过命令行解密Web.config
前端·学习·安全·web安全·矩阵·.net
Hellc0071 小时前
MacOS升级ruby版本
前端·macos·ruby
前端西瓜哥1 小时前
贝塞尔曲线算法:求贝塞尔曲线和直线的交点
前端·算法
又写了一天BUG1 小时前
npm install安装缓慢及npm更换源
前端·npm·node.js