超实用!50+个ChatGPT提示词助你成为高效Web开发者(上)

1cc975a7b26ff2d15da10cf650a536a3.jpeg如果你已经感到编写代码的重复和繁琐让你疲惫不堪,想要提高自己的效率,那么你来对地方了。ChatGPT是一款能够帮助你优化工作流程、减少错误并获得提高代码的见解的强大工具。

在这篇博客文章中,我们将向你提供超过50个提示和策略,以帮助你通过使用ChatGPT来加速你的Web开发工作流程。从初学者学习概念到准备面试,你将找到一切你需要的东西,使得AI成为你作为Web开发人员的不二之选。

然而,在探索这个令人兴奋的AI驱动的Web开发世界之前,首先要了解ChatGPT的局限性。虽然它是一款强大的工具,但它不能代替你自己的知识和技能。你也需要对ChatGPT为你提供的任何研究进行事实核查,因为它不能验证事实。此外,它的训练数据只更新到2021年,所以可能不了解当前的趋势或事件。但是,只要你记住这些要点,我们就可以开始深入探索这个激动人心的AI驱动的Web开发世界了。

一、代码生成

ChatGPT可以为各种Web开发任务生成代码,节省你的时间,帮助你更高效地工作。它可以帮助你生成语义化的HTML和CSS代码、JavaScript函数,甚至是数据库查询。

1、页面布局

提示词:

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

提示:生成一个语义化且无障碍的HTML和(框架)CSS [UI组件],由[组件部件]组成。[组件部件]应该是[布局]。

Example: Generate a semantic HTML and Tailwind CSS "Contact Support" 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“联系支持”表单,包括用户的姓名、电子邮件、问题类型和消息。表单元素应该垂直堆叠,并放置在一个卡片内。

<div class="bg-white rounded-lg shadow-lg p-6">
  <h2 class="text-lg font-medium mb-4">联系支持</h2>
  <form>
    <div class="mb-4">
      <label class="block text-gray-700 font-medium mb-2" for="name">
        姓名
      </label>
      <input class="form-input rounded-md shadow-sm block w-full" id="name" type="text" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-medium mb-2" for="email">
        电子邮件
      </label>
      <input class="form-input rounded-md shadow-sm block w-full" id="email" type="email" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-medium mb-2" for="type">
        问题类型
      </label>
      <select class="form-select rounded-md shadow-sm block w-full" id="type" required>
        <option value="" disabled selected>请选择问题类型</option>
        <option value="technical">技术问题</option>
        <option value="billing">账单问题</option>
        <option value="other">其他问题</option>
      </select>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-medium mb-2" for="message">
        消息
      </label>
      <textarea class="form-textarea rounded-md shadow-sm block w-full" id="message" rows="3" required></textarea>
    </div>
    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" type="submit">
      提交
    </button>
  </form>
</div>

2、编写JS工具函数

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

提示:编写一个JavaScript函数。它接受[输入]并返回[输出]。

Example: Write a JavaScript function. It accepts a full name as input and returns avatar letters.

示例:编写一个JavaScript函数。它接受完整的姓名作为输入,并返回头像字母。

function getAvatarLetters(fullName) {
  let names = fullName.split(" "); // split the full name into an array of names
  let initials = names.map(name => name.charAt(0)); // get the first letter of each name
  return initials.join("").toUpperCase(); // join the initials and convert to upper case
}

let fullName = "John Doe";
let avatarLetters = getAvatarLetters(fullName);
console.log(avatarLetters); // Output: "JD"

3、编写API

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

提示:为[功能]编写一个[框架]API。它应该利用[数据库]。

Example: Write an Express.js API to fetch the current user's profile information. It should make use of MongoDB.

示例:编写一个Express.js API来获取当前用户的个人资料信息。它应该利用MongoDB。

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const app = express();
const port = 3000;

// MongoDB connection string and database name
const url = 'mongodb://localhost:27017';
const dbName = 'mydatabase';

// Middleware to parse request body as JSON
app.use(express.json());

// Route to get current user's profile information
app.get('/users/:id', async (req, res) => {
  try {
    const client = await MongoClient.connect(url);
    const db = client.db(dbName);
    const collection = db.collection('users');
    const userId = new ObjectId(req.params.id);
    const user = await collection.findOne({ _id: userId });
    res.json(user);
    client.close();
  } catch (err) {
    console.log(err);
    res.status(500).send('Internal Server Error');
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

4、编写SQL语句

Prompt: 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门课程的学生列表。

SELECT s.student_id, s.first_name, s.last_name, COUNT(*) AS num_courses
FROM students AS s
JOIN course AS c
ON s.student_id = c.student_id
GROUP BY s.student_id, s.first_name, s.last_name
HAVING COUNT(*) >= 3;

二、代码自动完成

凭借人工智能的强大能力,ChatGPT还可以为您提供与您的上下文和风格相匹配的代码自动完成建议。

英文提示:Complete the code

中文提示:

完成以下代码:

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;
}

运行提示词咒语

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;
  case "cats":
    console.log(
      "Cats are independent creatures that can be affectionate and playful, but also enjoy their alone time. Their purring is a soothing sound that can help relieve stress."
    );
    break;
  case "birds":
    console.log(
      "Birds come in many different colors and sizes, and some species are known for their beautiful songs. They can make great pets if you are willing to provide them with proper care and attention."
    );
    break;
  case "fish":
    console.log(
      "Fish are fascinating creatures that come in a wide variety of shapes and colors. They can be kept as pets in aquariums, and some people even enjoy fishing as a recreational activity."
    );
    break;
  default:
    console.log(
      "I'm not sure what animal that is. Can you tell me more about it?"
    );
    break;
}

通常情况下,在您的提示结尾加上冒号,并将您的代码块粘贴到新的一行中是一个好的习惯。用三个反引号``` [code]``` 或三个双引号 """[code]""" 来分隔代码块也是一个不错的选择。

三、代码转换

作为开发人员,您可能需要处理用不同语言或框架编写的代码。使用 ChatGPT,您可以轻松地将代码片段从一种语言或框架转换为另一种语言或框架。

1、JS转TS

Prompt: Convert the below code snippet from [language/ framework] to [language/ framework]: [code snippet]

提示:将以下代码片段从[语言/框架]转换为[语言/框架]:[代码片段]

Example: Convert the below code snippet from JavaScript to TypeScript

示例:将以下代码片段从JavaScript转换为TypeScript

function nonRepeatingWords(str1, str2) {
  const map = new Map();
  const res = [];
  // Concatenate the strings
  const str = str1 + " " + str2;
  // Count the occurrence of each word
  str.split(" ").forEach((word) => {
    map.has(word) ? map.set(word, map.get(word) + 1) : map.set(word, 1);
  });
  // Select words which occur only once
  for (let [key, val] of map) {
    if (val === 1) {
      res.push(key);
    }
  }
  return res;
}

运行提示词咒语

function nonRepeatingWords(str1: string, str2: string): string[] {
  const map = new Map<string, number>();
  const res: string[] = [];
  // Concatenate the strings
  const str = str1 + " " + str2;
  // Count the occurrence of each word
  str.split(" ").forEach((word) => {
    map.has(word) ? map.set(word, map.get(word)! + 1) : map.set(word, 1);
  });
  // Select words which occur only once
  for (let [key, val] of map) {
    if (val === 1) {
      res.push(key);
    }
  }
  return res;
}

2、CSS框架互转

使用[CSS框架]重构以下代码以使用[CSS框架]:[代码片段]

示例:使用Tailwind CSS将以下代码从Bootstrap转换:[代码片段]

四、代码解释

ChatGPT可以通过提供解释或回答特定问题来帮助您理解代码。当您需要处理他人编写的代码或尝试理解复杂的代码片段时,这可能会非常有用。

Prompt: Review the following [language] code for code smells and suggest improvements: [code block]

提示:请解释以下[语言]代码片段:[代码块]

Prompt: Identify any security vulnerabilities in the following code: [code snippet]

提示:这段代码是用来做什么的:[Stack Overflow上的被接受答案的代码]

五、代码重构

您是否曾经写过一个注释 "//todo: 重构这段代码" 但却从未实现过它?ChatGPT可以帮助您通过提供建议,使您的代码重构更加高效。

1、Prompt: Refactor the given [language] code to improve its error handling and resilience: [code block]

提示:重构以下[语言]代码以提高其错误处理和韧性:[代码块]

2、Prompt: Refactor the given [language] code to make it more modular: [code block]

提示:重构以下[语言]代码以使其更具模块性:[代码块]

3、Prompt: Refactor the given [language] code to improve performance: [code block]

提示:重构以下[语言]代码以提高性能:[代码块]

4、Prompt: Refactor the below component code to be responsive across mobile, tablet, and desktop screens: [code block]

提示:重构以下组件代码,使其在移动端、平板电脑和桌面屏幕上都具有响应性:[代码块]

5、Prompt: Suggest descriptive and meaningful names for variables and functions, making it easier to understand the purpose of each element in your code: [code snippet]

提示:为变量和函数提供描述性和有意义的名称,使每个元素的目的更易于理解:[代码片段]

6、Prompt: Suggest ways to simplify complex conditionals and make them easier to read and understand: [code snippet]

提示:简化复杂条件语句,并使其更易于阅读和理解:[代码片段]

六、Bug检测和修复

作为开发人员,我们知道很难在代码中捕捉到所有的错误。但是,借助ChatGPT提示的帮助,我们可以轻松地识别和解决可能会导致问题的顽固错误。

Prompt: Find any bugs in the following code: [code snippet]

提示:查找以下代码中的任何错误:[代码片段]

Prompt: I am getting the error [error] from the following snippet of code: [code snippet]. How can I fix it?

提示:我在以下代码片段中遇到了错误[error],我该如何修复它?

七、系统设计和架构

ChatGPT可以提供有价值的见解和建议,如何使用特定的技术堆栈设计系统或将设计和架构与不同的技术堆栈进行对比。无论您正在构建Web应用程序、移动应用程序还是分布式系统,ChatGPT都可以帮助您设计一个可扩展、可靠且易于维护的架构,以满足您的需求。

1、设计一个系统

Prompt: You are an expert at system design and architecture. Tell me how to design a [system]. The technology stack is [comma-separated list of technologies].

提示:您是系统设计和架构的专家。告诉我如何设计一个[系统]。技术堆栈是[逗号分隔的技术列表]。

Example: You are an expert at system design and architecture. Tell me how to design a hotel reservation system. The technology stack is Next.js and Firebase.

示例:您是系统设计和架构的专家。告诉我如何设计一个酒店预订系统。技术堆栈是Next.js和Firebase。

运行提示词咒语后的效果:

设计一个酒店预订系统涉及到多个方面,比如管理房间库存、管理预订、处理支付、管理客户数据以及为客户和管理员提供用户界面。由于你选择了Next.js和Firebase,我将描述一个使用这些技术的高级架构。

Next.js是一个React框架,可以用来创建应用程序的前端,而Firebase可以用于后端,利用其各种服务,如Firestore数据库,Firebase Authentication进行用户管理,以及Cloud Functions提供无服务器计算能力。

前端 - Next.js: 系统的前端应该设计得易于用户(客人和酒店员工)使用。前端可以分为两个主要部分:

a. 客人界面:客人用这个界面进行预订,管理他们的预订,以及支付。它应该包括浏览可用房间、预订、修改/取消预订和付款等功能。

b. 员工界面:酒店员工用这个界面来管理房间库存、管理预订、查看报告等。它应该包括添加/删除/修改房间详情、查看所有预订、管理预订等功能。

后端 - Firebase:

a. Firestore:这是Firebase提供的一个NoSQL数据库。你可以创建以下集合:

- **Rooms**:用于存储酒店的所有房间。这个集合中的每个文档都代表一个房间,会有房间ID、房间类型、价格、是否可用等字段。

- **Bookings**:用于存储所有的预订。这个集合中的每个文档都代表一个预订,会有预订ID、客人ID、房间ID、预订日期、入住日期、退房日期等字段。

- **Users**:用于存储所有的用户(客人和员工)。这个集合中的每个文档都代表一个用户,会有用户ID、姓名、电子邮件、密码、角色(客人或员工)等字段。

b. Firebase Authentication:你可以用它来处理用户注册和登录。Firebase Authentication支持多种登录方法,包括电子邮件/密码、手机号、以及各种社交登录。

c. Cloud Functions:你可以用它来处理那些不能在客户端完成的工作,比如在预订时检查房间的可用性、处理支付等。

支付:你可以使用Firebase的Cloud Functions集成一个第三方支付服务,比如Stripe,来处理支付。

安全性:确保所有的数据传输都是加密的,并且只有经过验证和授权的用户才能访问相关数据。

以上是一个高级的系统设计和架构,实际的实现可能会根据你的具体需求进行调整。

2、架构对比

Prompt: Contrast the design and architecture with [comma-separated list of technologies] as the technology stack.

提示:将上述的设计和架构与[逗号分隔的技术列表]作为技术堆栈进行对比。

Example: Contrast the design and architecture with React and Supabase as the technology stack.

示例:将上述的设计和架构与React和Supabase作为技术堆栈进行对比。

运行提示词咒语后的效果:

前端 - React:React是一个用于构建用户界面的JavaScript库。与Next.js一样,你仍然可以为客人和员工创建一个丰富、交互式的前端。React有一个庞大的社区和丰富的第三方库生态系统,可以帮助构建复杂的界面。

后端 - Supabase:Supabase是Firebase的替代品,提供了一整套工具,包括实时数据库、身份验证、存储和无服务器函数。Supabase使用的是PostgreSQL,这是一种关系数据库,与Firebase的Firestore(一种NoSQL数据库)不同。

a. Supabase数据库(PostgreSQL):你将使用表格而不是集合。你可以为房间、预订和用户设置表格,并定义它们之间的关系。

- **Rooms**:这个表格中的每一行都将代表一个房间,会有房间ID、房间类型、价格和可用性等列。

- **Bookings**:这个表格中的每一行都将代表一个预订,会有预订ID、客人ID、房间ID、预订日期、入住日期和退房日期等列。

- **Users**:这个表格中的每一行都将代表一个用户(客人或员工)。它会有用户ID、姓名、电子邮件、密码和角色(客人或员工)等列。

b. Supabase Auth:这将用于处理用户注册和登录,类似于Firebase Authentication。Supabase Auth也支持多种登录方式,包括电子邮件/密码和各种社交登录。

c. Supabase Storage:这可以用于存储任何静态文件,如房间的图片。

d. 无服务器函数:Supabase提供了Postgres函数,可以类似于Firebase的Cloud Functions用于服务器端操作,如在预订时检查房间的可用性、处理支付等。

支付:你仍然可以集成一个第三方支付服务,如Stripe,来处理支付。

安全性:与Firebase设置类似,确保所有数据传输都是加密的,只有经过认证和授权的用户才能访问相关数据。

在架构方面,这两种设置都提供了构建可扩展和安全应用程序的方式。Firebase使用的是NoSQL数据库,可能更适合非结构化数据,而Supabase使用的是PostgreSQL,更适合结构化的关系数据。在这两种堆栈之间的选择可能会受到你的团队的专业知识、数据的性质以及你的特定用例的影响。

例如,如果你的数据需要复杂的查询和严格的关系完整性,PostgreSQL可能是一个更好的选择。同时,Supabase的Postgres函数使得你可以在数据库层面执行更多的业务逻辑,这可能会简化应用程序的设计和实现。

然而,如果你的数据结构更加动态和灵活,或者你需要高度的读写扩展性,Firebase的Firestore可能会更适合。

此外,你还应考虑你的团队对这两种技术的熟悉程度。虽然React和Next.js都是基于JavaScript的,但它们在某些方面是有区别的。例如,Next.js提供了服务器端渲染和静态站点生成等功能,这可能会影响你的选择。

总的来说,虽然这两种技术堆栈在某些方面存在差异,但它们都可以用于构建一个酒店预订系统。你的最终选择应基于你的具体需求、数据结构以及团队的技术背景。

八、搜索引擎优化

ChatGPT 可以为您提供优化网站以适应搜索引擎的提示和最佳实践。

Prompt: How to improve SEO for a landing page?

提示:如何改进着陆页的搜索引擎优化?

运行提示词咒语后的效果:

关键词研究:首先,进行关键词研究,找出与落地页主题相关的关键词。使用Google关键词规划工具等工具来帮助您找到正确的关键词。

优化标题和描述:在HTML标题标签和描述标签中使用关键词,以便搜索引擎更好地理解页面内容。确保标题和描述吸引人,并鼓励人们点击链接。

优化内容:使用关键词在落地页内容中,并确保它们自然地融入内容中。确保内容易于阅读,并使用有序列表和短段落来提高可读性。

内部链接:在网站内部链接到落地页。这有助于分配权重并提高页面的排名。

链接建设:从其他网站链接到您的落地页。这可以帮助提高您的页面排名,并向搜索引擎传达您的网站的价值和权威性。

Prompt: Give an example <head> section of the HTML code that is optimized for Search Engine Optimization (SEO) for a [website]

提示:给出一个已经针对搜索引擎优化 (SEO) 的 HTML 代码中 <head> 部分的例子,用于优化 [网站] 的搜索引擎优化。

Example: Give an example <head> section of the HTML code that is optimized for Search Engine Optimization (SEO) for a social networking site for athletes
示例:给出一个已经针对搜索引擎优化 (SEO) 的 HTML 代码中 <head> 部分的例子,用于优化运动员社交网络网站的搜索引擎优化。

运行提示词咒语后的效果:

<head>
  <title>运动员社交网络 - 共享体验</title>
  <meta name="description" content="运动员社交网络是一个为运动员提供互动和交流平台的网站。加入我们,共享您的经验和知识。">
  <meta name="keywords" content="运动员, 社交网络, 交流平台">
  <meta name="author" content="运动员社交网络">
  <link rel="canonical" href="https://www.athletenetwork.com/">
</head>

九、生成测试用的模拟数据

无论是用于测试还是演示目的,拥有逼真和具有代表性的数据非常重要。ChatGPT可以帮助您快速生成各种领域和格式的模拟数据。

Prompt: Generate a sample [data format] of [number] [entity] for a [domain]

提示:为一个 [领域] 生成 [数量] 个 [实体] 的样本 [数据格式]

Example: Generate a sample JSON of 5 products for a clothing e-commerce site

示例:为服装电子商务网站生成5个产品的JSON样本

运行提示词咒语后的效果:

在创建产品的JSON样本时,我们通常包括产品的一些关键信息,如id、名称、描述、价格、库存数量、图片URL等。以下是5个服装电子商务网站产品的JSON样本:

[
    {
        "id": "1",
        "name": "Black Leather Jacket",
        "description": "Men's black leather jacket in biker style.",
        "price": 120.00,
        "stock": 10,
        "imageUrl": "https://example.com/images/product1.jpg",
        "category": "Men's Clothing"
    },
    {
        "id": "2",
        "name": "Blue Denim Jeans",
        "description": "Women's high waist slim fit denim jeans.",
        "price": 50.00,
        "stock": 20,
        "imageUrl": "https://example.com/images/product2.jpg",
        "category": "Women's Clothing"
    },
    {
        "id": "3",
        "name": "Grey Running Shoes",
        "description": "Unisex grey running shoes with cloudfoam technology.",
        "price": 70.00,
        "stock": 15,
        "imageUrl": "https://example.com/images/product3.jpg",
        "category": "Footwear"
    },
    {
        "id": "4",
        "name": "Striped T-Shirt",
        "description": "Kid's striped t-shirt in 100% cotton.",
        "price": 20.00,
        "stock": 30,
        "imageUrl": "https://example.com/images/product4.jpg",
        "category": "Kid's Clothing"
    },
    {
        "id": "5",
        "name": "Red Silk Dress",
        "description": "Women's red silk dress with a bow tie.",
        "price": 200.00,
        "stock": 5,
        "imageUrl": "https://example.com/images/product5.jpg",
        "category": "Women's Clothing"
    }
]

Prompt: You can also enter prompts after every response for more fine-grained control

Give me a list of [number] fields for [entity] on an e-commerce site

Add an “id” field that will be unique to each [entity]. Replace [existing field] with [new field]

Generate a sample [data format] of [number] such [entity] with realistic values

中文提示:您还可以在每个响应后输入提示,以获取更精细的控制

给出电子商务网站上 [实体] 的 [数量] 个字段的列表

添加一个“id”字段,每个[实体]都是唯一的。

用 [新字段] 替换 [现有字段] 生成一个具有逼真值的 [数量] 个 [实体] 的样本 [数据格式]

运行提示词咒语后的效果:

您似乎正在寻找一种结构化的方式来创建电子商务网站的实体。让我们用 "Product"(产品)作为 [实体] 的示例。

给出电子商务网站上产品的10个字段的列表。

id: 每个产品的唯一标识符。

name: 产品的名称。

description: 产品的详细描述。

price: 产品的价格。

stock: 库存的产品数量。

imageUrl: 产品图片的URL。

category: 产品所属的类别。

color: 产品的颜色。

size: 产品的大小。

weight: 产品的重量。

添加一个“id”字段,每个产品都是唯一的。

用 [新字段] 替换 [现有字段]。

例如,如果您想将 "imageUrl" 字段替换为 "imagePath" 字段,那么新的产品实体可能看起来像这样:

id: 每个产品的唯一标识符。

name: 产品的名称。

description: 产品的详细描述。

price: 产品的价格。

stock: 库存的产品数量。

imagePath: 产品图片的路径。

category: 产品所属的类别。

color: 产品的颜色。

size: 产品的大小。

weight: 产品的重量。

生成一个具有逼真值的5个产品的样本JSON。

[
    {
        "id": "001",
        "name": "黑色皮夹克",
        "description": "男式黑色骑行风格的皮夹克。",
        "price": 120.00,
        "stock": 10,
        "imagePath": "/images/product1.jpg",
        "category": "男装",
        "color": "黑色",
        "size": "L",
        "weight": "1.2kg"
    },
    {
        "id": "002",
        "name": "蓝色牛仔裤",
        "description": "女式高腰修身牛仔裤。",
        "price": 50.00,
        "stock": 20,
        "imagePath": "/images/product2.jpg",
        "category": "女装",
        "color": "蓝色",
        "size": "M",
        "weight": "0.5kg"
    }
  // 省略

结束

由于文章内容篇幅有限,今天的内容就分享到这里,在下篇文章将继续分享剩余的部分,敬请期待。

文章结尾,我想提醒您,文章的创作不易,如果您喜欢我的分享,请别忘了点赞和转发,让更多有需要的人看到。同时,如果您想获取更多前端技术的知识,欢迎关注我,您的支持将是我分享最大的动力。我会持续输出更多内容,敬请期待。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>