How to use GitHub Copilot in VS Code to improve programming efficiency

This article was first published on the official account: More AI (power_ai), welcome to pay attention, programming and AI dry goods will be delivered in time!

Get started with GitHub Copilot in Visual Studio Code

GitHub Copilot is an AI pair programming tool. It's a fancy way of saying it is a "second programmer" that works inside your source code editor. As you write code, Copilot will give suggestions in the form of auto-completion to help you write code faster and more efficiently.

This article walks you through installing and setting up GitHub Copilot in Visual Studio Code. Then, you'll learn how to use Copilot to speed up the programming process.

Require

To use GitHub Copilot, you need to have a GitHub account. If you haven't already, you can sign up for an account on the official website .

Before signing up for GitHub Copilot , make sure you are logged into your GitHub account. The service offers a 30-day free trial, after which you'll need to subscribe to one of the paid plans.

Screenshot of the GitHub copilot authorization page

If you have no intention of subscribing to a paid plan, then please cancel GitHub Copilot before the trial ends to avoid getting billed.

Finally, you need to have Visual Studio Code installed on your local machine. To install Visual Studio Code, visit the official VS Code download page .

Install the GitHub Copilot extension

First, start your Visual Studio Code editor. Next, click on the Extensions tab. Search for GitHub Copilot in the search box . Install and activate the extension (it has over 5 million downloads at the time of writing):

Once the extension is fully activated, a prompt will appear telling you to log into GitHub. Click the button to log in. The authentication process will be quick since you are already logged into GitHub and GitHub Copilot. If the process was successful, you will find the Copilot icon in the bottom right corner of VS Code.

Ask a technical question to Copilot

Although Copilot is billed as a coding assistant, you can ask it technical questions directly. It's perfect if you're preparing for a technical interview and want quick answers to common interview questions.

To ask GitHub Copilot questions, put your question in a comment starting with **:q**:

// q: 对象导向编程中的类是什么?

Once you see Copilot's suggestion (grayed out), hit the Tab key on your keyboard to accept it as your answer. The answer is preceded by **:a**. The Tab key works on both Windows and Mac computers.

You can also ask one of these answers specifically to get more information about it. Copilot predicts what you're about to ask and autocompletes the questions for you.

Copilot with HTML and CSS

Now let's turn our attention to coding, starting with an HTML example. Copilot can help speed up the process of writing HTML. Let's see how.

Create two HTML files in your project. The files should be named example1.html and example2.html . Next, open the example1.html file in VS Code .

First type ****Document Type Declaration. When you hit Enter on your keyboard , Copilot already knows that the `` tag will be the next obvious one to add. So it suggests adding tabs (hit Tab to accept).

After that, Copilot suggests you add ,然后是. It closes <head>, sure enough, <body>and <h1>tags and paragraphs are suggested to be added.

If you want to generate an element, you just describe the element you want to generate in a comment and press Tab . Here is an example:

 <!-- 一个内联蓝色标题的h1 -->

This will generate an element with blue text <h1>:

<h1 style="color:blue">这是一个蓝色的标题</h1>

You can also ask to create a bulleted list, using the following tips:

<!-- 创建一个项目符号列表 -->

Here is the result:

<ul>
    <li>第一项</li>
    <li>第二项</li>
    <li>第三项</li>
</ul>  

As a best practice, styles should always be in a single stylesheet. Create a styles.css file in the same folder as the HTML file .

The following hints will generate link elements referencing style sheets. <head>Write this hint inside a tag in HTML :

<!-- 引用名为style.css的样式表 -->

This will be the output:

<link rel="stylesheet" type="text/css" href="style.css">

If the stylesheet files are inside another folder, just describe the directory structure in your prompt and Copilot will hrefuse the correct URL in it.

Copilot helps with Bootstrap

With a simple "Add Bootstrap" prompt, Copilot will generate a link referencing Bootstrap on the CDN. This is much more convenient than searching the web for the latest links to Bootstrap.

Copilot also applies Bootstrap classes to your elements. When you start an <div>element and press spacebar, Copilot knows you most likely want to add alertand alert-successclass, so it will suggest to add.

<div class="alert alert-success">
    <strong>成功!</strong>这个警告框代表了一个成功或积极的行动
</div>

Just press Tab to accept suggestions.

Simplify regular expressions with Copilot

If you've ever worked with regular expressions, you probably know how difficult it is to decipher these patterns. But with Copilot by your side, writing regular expressions is a lot easier because you can ask Copilot to write specific patterns for you.

For example, if you want to write a regular expression that matches phone numbers, you can write the following prompt in your JavaScript file:

// 用正则表达式匹配这种格式的电话号码 (xxx) xxx-xxxx

If you press Enter on your keyboard , Copilot will give you the regular expression you requested:

var phoneRegex = /^\(\d{3}\) \d{3}-\d{4}$/;

Regular expressions are often used for testing, which is what the next section is about.

Copilot makes unit testing easy

Copilot makes unit testing very easy. Let's look at an example.

The following function takes a string, checks for a match to a regular expression, and parses the first and last values, then concatenates the numbers according to the operator:

function calculator(str) {
var regex = /^\(\d{3}\) \d{3}-\d{4}$/;
var match = str.match(regex)

var num1 = parseInt(match[1])
var num2 = parseInt(match[3])

switch (match[2]) {
case "+":  
return num1 + num2;
case "-":  
return num1 - num2;
case "*":  
return num1 * num2;
case "/":  
return num1 / num2;
default:
return "无效的运算符";
}
}

Now you can tell Copilot console.log()to test the function with a hint like this:

// 测试 calculator 函数

Copilot will record each operation and give output:

console.log("1+1") // 2
console.log("1-1") // 0
console.log("1*1") // 1
console.log("1/1") // 1

For the prompt below, Copilot will generate code for unit testing the function:

// 创建 calculator 函数的单元测试
var assert = require("asser")
assert.equal(calculator("1+1"), 2, "calculator可以进行加法")

Not only does it generate code, but it also suggests tests for other operations besides addition.

Choose from multiple solutions by Copilot

So far, we've seen Copilot give some advice. But always remember that you don't always have to choose the first suggestion. If you don't like the first option, you can always choose another one.

Consider the following tips:

// 创建一个函数,该函数接收一个字符串并返回其反向字符串

Start pressing Tab to see suggestions. If you are not satisfied with the first suggestion, hover over the text and navigate to the next solution (use the ** > icon). Once you find an acceptable solution, you can click the Accept** button.

Screenshot of Copilot function autocompletion

Prompting Copilot with multiple conditions

When writing your Copilot prompt, you can specify multiple conditions. This is very useful if you want to write a complex program with different rules.

Say you want to parse a list of expenses with some conditions. Inside the function, you'll ask Copilot to do three things in your prompt (indicated by comments):

function parseExpenses(expenses) {
  /* 解析费用清单并返回由三元组(日期、数值、货币)组成的数组。忽略以//开始的行。
使用Date()解析日期
  */
}

Here we have specified three conditions: parsing manifest, ignoring comments, parsing date. Press Control-Enter and choose the best solution from the suggestions.

When I tested, one of the suggestions was:

   return expenses.split("\n")
    .filter(line => !line.startsWith("//"))
    .map(line => line.split(","))
    .map(([date, value, currency]) => [new Date(date), Number(value), currency]);

That's great. But beware - some of the suggestions made to me use <string> line[0]=="/"to test which lines should be ignored. This is not what we asked for!

When reading the code generated by Copilot or any other AI tool, it is very important to make sure it does what you expect.

in conclusion

In this tutorial, we learned the basics of using GitHub Copilot. Just write your tip in the comments and hit Control-Enter to see the suggestions.

Hello, I am Shisan, a veteran driver who has been developing for 7 years, and a foreign company for 5 years in the Internet for 2 years. I can beat Ah San and Lao Mei, and I have also been ruined by PR comments. Over the years, I have worked part-time, started a business, took over private work, and mixed upwork. Made money and lost money. Along the way, my deepest feeling is that no matter what you learn, you must keep learning. As long as you can persevere, it is easy to achieve corner overtaking! So don't ask me if it's too late to do what I do now. If you still have no direction, you can follow me [public account: More AI (power_ai)], where I will often share some cutting-edge information and programming knowledge to help you accumulate capital for cornering and overtaking.

Guess you like

Origin blog.csdn.net/smarter_AI/article/details/131745033