diff --git a/Using-GitHub-Copilot-with-JavaScript/README.MD b/Using-GitHub-Copilot-with-JavaScript/README.MD index 3fa150e..cf39cd4 100644 --- a/Using-GitHub-Copilot-with-JavaScript/README.MD +++ b/Using-GitHub-Copilot-with-JavaScript/README.MD @@ -2,161 +2,203 @@ # Using GitHub Copilot with JavaScript -In this module, we’ll explore the powerful capabilities of GitHub Copilot and discover how it can transform your coding experience. Picture writing code more efficiently, with less effort—GitHub Copilot turns this vision into reality by generating intelligent suggestions based on the context of your comments and code. +In this hands-on module, you'll master GitHub Copilot's powerful features—from basic code completions to advanced agent capabilities and customization options. You'll learn to leverage AI assistance effectively in your development workflow, exploring how Copilot can understand context, generate complex code structures, and adapt to your specific needs through custom instructions and contextual knowledge. -As a developer aiming to boost productivity, you’ll delve into mastering GitHub Copilot, focusing on its applications in JavaScript. By the end of the module, you’ll have the skills to craft effective prompts that drive valuable suggestions using the GitHub Copilot extension in Visual Studio Code. You’ll enhance a JavaScript project, experiencing how this AI-powered tool provides autocomplete-style suggestions, streamlining your development process. +By the end of this workshop, you'll transform from a Copilot beginner to a power user, capable of crafting precise prompts, utilizing autonomous coding agents, and customizing Copilot to match your team's unique requirements. -Mastering GitHub Copilot doesn’t stop at coding assistance—you’ll also learn to configure repositories in Codespaces and harness this AI tool to optimize your projects. Get ready to revolutionize your workflow, elevate your coding skills, and unlock a new level of productivity in this dynamic learning journey! +This module can be completed in about an hour. +By the end of this module, you’ll be able to: +- Use Copilot’s code generation features, such as Next Edit Suggestions and Agent mode. +- Customize Copilot’s responses with custom instructions, prompt files, and chat modes. +- Understand the purpose of MCP, configure an MCP server, and use MCP tools. -- **Who this is for**: Developers, DevOps Engineers, Software development managers, Testers. -- **What you'll learn**: Using GitHub Copilot to create code and add comments to your work. -- **What you'll build**: JavaScript files that will have code generated by Copilot AI for code and comment suggestions. -- **Prerequisites**: GitHub Copilot is available to use for free, sign up for [GitHub Copilot](https://gh.io/copilot). -- **Timing**: This module can be completed in under an hour. +## 📖 Prerequisite reading +- [Introduction to prompt engineering with GitHub Copilot](https://learn.microsoft.com/training/modules/introduction-prompt-engineering-with-github-copilot//?WT.mc_id=academic-113596-abartolo) +- [Using GitHub Copilot with JavaScript](https://learn.microsoft.com/training/modules/introduction-copilot-javascript/?WT.mc_id=academic-113596-abartolo) -By the end of this module, you'll aquire the skills to be able to: -- Craft prompts to generate suggestions from GitHub Copilot -- Apply GitHub Copilot to improve your projects. +## 📋 Requirements +1. Enable your [GitHub Copilot service](https://github.com/github-copilot/signup) +1. Open [this repository with Codespaces](https://codespaces.new/github-samples/node-recipe-app?quickstart=1) -## Prerequisite reading: -- [Introduction to prompt engineering with GitHub Copilot](https://learn.microsoft.com/training/modules/introduction-prompt-engineering-with-github-copilot//?WT.mc_id=academic-113596-abartolo) -- [Using GitHub Copilot with JavaScript](https://learn.microsoft.com/training/modules/introduction-copilot-javascript/?WT.mc_id=academic-113596-abartolo) +**Right click the following Codespaces button to open your Codespace in a new tab** +[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/github-samples/node-recipe-app?quickstart=1) -## Requirements +This application is a recipe app that allows users to create, edit, and read recipes. Before this module, there are notable missing features including the ability to delete and search recipes. But don’t worry, Copilot is here to help! -1. Enable your [GitHub Copilot service](https://github.com/github-copilot/signup) -1. Open [this repository with Codespaces](https://codespaces.new/MicrosoftDocs/mslearn-copilot-codespaces-javascript?quickstart=1) +## 🧑‍💻 Section 1: Exploring your project +**🎯 Learning Goals** +- Understand how to use Copilot Chat for codebase exploration. +- Be able to use built-in slash commands for common operations. -## 💪🏽 Exercise +Once your Codespace launches, you'll have a fully functional development environment with the entire repository preloaded. This is the perfect time to explore GitHub Copilot Chat to help you better understand the codebase. -**Right click the following Codespaces button to open your Codespace in a new tab** +Click the Copilot Chat icon in the top-right corner of the Codespace window Open GitHub Copilot Chat. Make sure that Agent is selected in the mode selection dropdown. -[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=526682619) +![Codespaces UI with an arrow pointing to a Copilot icon in the top bar to the right of the command center.](./images/activate-chat.png) -In this template portfolio, we have a React based web application ready for you to easily customize and deploy using only your web browser. +Instead of manually exploring the various files across directories, try asking Copilot for an overview. In the chat pane, type '/' to view available slash commands — these offer quick, structured ways to interact with Copilot. -**Note:** Please disregard the instructions given within the GitHub Codespace. For this exercise, be sure to follow the instructions found here. +Type '/help' to see all commands, or check out the [GitHub Copilot Chat cheat sheet](https://docs.github.com/copilot/reference/github-copilot-chat-cheat-sheet#slash-commands) for a list of slash commands available. For example, you can use: +- `/doc` to add a documentation comment +- `/explain` to explain the code +- `/fix` to propose a fix for the problems in the selected code +- `/generate` to generate code to answer your question -### 🛠 Step 1: Customize the web app +You can also provide files or blocks of code as context. Open `src/database/seedData.js` and then type `/explain` in the chat pane. By default, the currently open editor will be added to context. If specific parts of the file are selected, only that text will be added as context. -Customize the portfolio with your own links. Go to `src/App.jsx` and update the `siteProps` with your information. The `siteProps` variable is a JavaScript object that holds key value pairs used to customize the site, it should look like this: +![The editor has the seed data file open and the Copilot chat wildow has only the prompt slash explain. The response provides and explanation of the file in sections.](./images/explain-file.png) -```javascript -const siteProps = { - name: "Alexandrie Grenier", - title: "Web Designer & Content Creator", - email: "alex@example.com", - gitHub: "microsoft", - instagram: "microsoft", - linkedIn: "satyanadella", - medium: "", - twitter: "microsoft", - youTube: "Code", -}; -``` -### 📖 Step 2: Explain the code - -Now lets use the slash command to explain what a portion of the code does. Highlight the following code: - -```javascript -}; - -const primaryColor = "#4E567E"; -const secondaryColor = "#D2F1E4"; - -const App = () => { - return ( -
-
- - - -
- ); -}; -``` -Once highlighted, hit Ctrl + I (Windows) or Cmd + I (Mac) and enter **/explain**. You should receive a response in the Copilot Chat window similar to this: +## 🧑‍💻 Section 2: Code completion -``` -This JavaScript code is written in React, a popular library for building user interfaces. The code defines a functional component named App. The App component is the root component of your application. It's where all other components (Header, Home, About, Portfolio, Footer) are being called and rendered. The App component returns a JSX (JavaScript XML) structure, which looks similar to HTML. This JSX structure defines what the App component should render on the screen. In the JSX, there is a div with an id of "main". Inside this div, several components are being rendered: Header, Home, About, Portfolio, and Footer. The Home component is being passed two props: name and title, both of which are properties of the siteProps object. The Footer component is being passed several props. The ...siteProps syntax is using the JavaScript spread operator to pass all properties of siteProps as separate props. In addition to the siteProps, two more props are being passed: primaryColor and secondaryColor. These are defined as constants at the top of the file. Remember, props (short for properties) in React are how components talk to each other. If you think of components as functions, then props are the arguments to these functions. They are passed from the parent component (in this case, App) to the child components (Header, Home, About, Portfolio, Footer). -``` +**🎯 Learning Goals** -Lets dive a little deeper. Notice how Copilot Chat now provides a follow up question suggestion for you to ask. Click on the question suggested by GitHub Copilot found at the bottom of the window usually starting with "What is the purpose..." and review the answer provided. As an example, should the question GitHub Copilot provide be the following: +- Use inline code completion to write code from comments. +- Trigger and refine Copilot completions. +- Use inline chat and slash commands. -What is the purpose of using props in React components? +In the previous section you learned how to use both natural language or slash commands to quickly understand the codebase without digging through folders. In the next set of exercises we're going to use Copilot to create a new route handler using code completion. -You should get an answer similar to this: +Open the `src/routes.js` file. Just above the final line where the router is exported, add the following comment: ``` -Props (short for properties) in React are used for passing data from one component to another, just like function arguments. They are read-only and help to make components reusable and dynamic. In your code, for example, the Home component is passed name and title as props. This means that the Home component can use these values to display dynamic content. The Footer component is also passed several props, including all properties of siteProps and the primaryColor and secondaryColor constants. Here's an analogy: think of a component as a custom HTML element and props as the attributes of that element. Just like you can pass different attributes to an HTML element (like An image), you can pass different props to a React component (like ). This makes your components more flexible and reusable. For instance, you could use the same Home component with different props to display different content. +// Get a random recipe ``` -Did you notice after you clicked the suggested question in the Copilot Chat windows, it used a command similar to the following to ask the question: +Copilot will suggest code - you can hit the tab key on your keyboard to accept the suggestion. Quite often, Copilot will only generate one or a few lines at a time with inline code completion and then suggest the following lines, so you may need to hit tab a few times to complete the route handler. + +![Underneath the comment is slightly transparent text with a suggestion.](./images/ghost-text.png) + +You can also open Copilot directly where you edit text for quick questions or modifications. Open the `src/routes.js` file and highlight the following code block: + +```js +router.get('/recipes', async (req, res) => { + const db = await getDbConnection() + const recipes = await db.all('SELECT * FROM recipes') + res.render('recipes', { recipes }) +}) +``` + +Press `CTRL + I` (Windows) or `CMD + I` (Mac) to open inline chat. This is a good place for small explanations or modification requests. Type “Sort by title” and hit enter. You should see a small change to the SQL query which you can accept or follow up with further requests. + +![A text box above the code block with the prompt "sort by title and a one line change. There is an accept and cancel button in the box."](./images/inline-edits.png) + +You can also enable Next Edit Suggestions in settings. Once enabled, Copilot analyses your code history, the structure of your codebase, conventions and behaviors, and predicts the logical next step after you make a change. Just like with code completion, you can hit tab to accept the change. + +![A green arrow is showing in the gutter of one of the lines.](./images/nes.png) + +## 🧑‍💻 Section 3: Agent mode + +**🎯 Learning Goals** + +- Implement a new feature autonomously in your code editor with GitHub Copilot Agent mode. + +Agent mode lets you hand Copilot a high-level prompt and then watch as it autonomously plans the steps, selects the right files, runs tools or terminal commands, and iterates on code edits until the task is complete. + +Agent mode runs within your code editor and will detail the steps it will take to complete the task in your prompt. Making sure that ‘Agent’ is selected in the Copilot Chat pane, provide the following prompt: ``` -@workspace /explain What is the purpose of using props in React components? +Implement the ability to delete recipes. Implement this using a HTML form and a new POST /recipes/:id/delete route handler. Make sure the buttons exist on both the recipe view and edit pages. Write tests for your work. ``` +![Step 1: select the mode dropdown from the Copilot chat input box. Step 2: select Agent.](./images/agent-mode.png) -The @workspace agent, like Copilot, fills in missing details, helping when humans overlook or don't fully describe everything they see. When prompted, Copilot takes a different approach. Instead of immediately responding, it first examines the files and folders in the workspace in steps: +Copilot will examine your codebase and then make requisite changes over multiple files, creating new ones if required. If Copilot wants to run terminal commands, it will ask. If tests fail, Copilot will recognize this and automatically continue work providing its reasoning. -1. It checks the names of files/folders to see which could be relevant. -2. It reads the contents of files, sometimes in full, sometimes partially due to memory limits. -3. It creates context from the collected information. -4. It responds, using both the prompt's context and the information it gathered. +## 🧑‍💻 Section 4: Customization & context +**🎯 Learning Goals** -### 🔎 Step 3: Animate the social media icons with a prompt +- Understand the different ways to customize GitHub Copilot. +- Understand the role of Model Context Protocol (MCP). -An animation can make the social media section more eye-catching. Ask Copilot’s help to animate the icons. Jump to the end of the file and write the following prompt in the `src/styles.css` file: +### Part 1: Custom Instructions -```css -/* add an amazing animation to the social icons */ -``` +GitHub Copilot instructions files are markdown documents that provide essential context to guide Copilot’s behavior within a specific codebase. -The suggestion from Copilot should look similar to the following: - -```css -img.socialIcon:hover { - animation: bounce 0.5s; - animation-iteration-count: infinite; -} - -@keyframes bounce { - 0% { - transform: scale(1); - } - 50% { - transform: scale(1.2); - } - 100% { - transform: scale(1); - } -} -``` +These files help tailor AI-generated suggestions to match your team’s coding standards, architectural patterns, naming conventions, testing strategies, and deployment practices. + +There are two types of instructions files: global instructions, which apply to the entire repository and are stored in `copilot-instructions.md`, and scoped instructions, which apply only to specific files or folders and are placed in `.github/instructions/*.instructions.md`. + +By supplying Copilot with detailed project context, instructions files significantly improve the relevance and accuracy of its code suggestions. For example, if your project uses specific libraries and frameworks, Copilot can generate components that follow your preferred structure, use modern JavaScript features, and adhere to your naming conventions. This leads to more consistent code and reduces the need for manual corrections or lengthy code reviews. + +Instructions files also enhance Copilot’s ability to generate meaningful tests and documentation. With the right context, Copilot can suggest unit tests. When refactoring or adding new features, Copilot respects your configuration, patterns, and error-handling strategies, making it a smarter and more reliable assistant. + +Beyond technical benefits, instructions files improve collaboration across teams. New contributors can rely on Copilot to guide them through unfamiliar codebases, ensuring they follow established practices without needing extensive onboarding. This makes instructions files a powerful tool for maintaining code quality, streamlining development workflows, and fostering team alignment. This contextual intelligence transforms Copilot from a generic code assistant into a project-aware collaborator. + +Global custom instructions file will be automatically included in every request in GitHub Copilot chat. To create one, create a `copilot-instructions.md` file in the `.github` directory: -### 🚀 Step 4: Find out how to run the app -Open GitHub Copilot chat by clicking on the chat icon on the left side bar and use the input section to ask the following: +```md +# GitHub Copilot Instructions +## Project Overview +This is a CRUD recipe application built with Node.js, Express, and Handlebars templating engine. The app allows users to create, read, update, and delete recipes with ingredients and cooking methods. + +## Technology Stack +- **Backend**: Node.js with Express.js +- **Database**: SQLite with custom database layer +- **Templating**: Handlebars.js +- **Testing**: Jest +- **Styling**: Vanilla CSS + +## Code Style Guidelines +- Use ES6+ features and async/await for asynchronous operations +- Follow RESTful routing conventions for recipe operations +- Use semantic HTML and BEM-style CSS classes where appropriate +- Keep database queries in the `src/database/` directory +- Store all view templates in the `views/` directory with Handlebars syntax + +## Key Patterns +- Database operations should use the custom connection layer in `src/database/` +- Routes are defined in `src/routes.js` following Express patterns +- Handlebars helpers for text formatting (split, newline, add) are available +- Use proper error handling for database operations and route handlers +- Follow the existing form structure for CRUD operations + +## Testing +- Test files are in `__tests__/` directory +- Use Jest for unit and integration testing +- Include tests for both database operations and route handlers +- Mock database connections in tests using the test setup files ``` -@workspace I want to understand how can I run this React application + +You can also create specific instruction files that will be automatically applied to only specific files or directories. They must be within a `.github/instructions` directory and end in `.instructions.md`. + +In the `.github` directory, create an `instructions` subdirectory. Within the subdirectory, create a `styling.instructions.md` file: + +```md +--- +applyTo: "public/*.css" +--- + +- Use semantic class names (`.recipe-*`, `.btn-*`, `.form-*`) +- Follow BEM methodology where appropriate +- Use consistent spacing units (8px, 16px, 24px) +- Use CSS custom properties for colors +- Mobile-first responsive design +- Use flexbox for layouts +- Ensure accessibility with proper contrast and focus states +- Ensure buttons have adequate touch targets (44px minimum) ``` -The prompts uses `@workspace` which is a special feature of GitHub Copilot chat that allows you to include more context for a more complete answer. Try out other queries using the chat panel for a more interactive workflow. +### Part 2: Model Context Protocol (MCP) + +Model Context Protocol (MCP) is a universal standard that allows AI tools to integrate and interact with external services. An MCP host can connect to one or more MCP servers, which in turn provide tools that an AI tools can utilize. + +GitHub Copilot Agent mode supports MCP, so you can connect to thousands of services. Microsoft provides many MCP servers, including ones for GitHub, Azure AI Foundry, and Playwright. They aren’t just for fetching data, but can perform complex operations with natural language and Copilot. -### Conclusion -Your site should already be running in your Codespace, and the change will reload onto the page automatically. To see them, hover over one of your social media icons in the footer to see the magic! +You can learn more about MCP and how to configure it using the dedicated [GitHub Skills course](https://github.com/skills/integrate-mcp-with-copilot) or deep dive with [MCP for Beginners](https://github.com/microsoft/mcp-for-beginners). -**Note:** Refresh the Codespace browser window if the hover effects do not work. +## 📘 Further learning -Congratulations, through the exercise, you have use GitHub Copilot to generate code and also done it in an interactive and fun way! You can use GitHub Copilot to not only generate code, but write documentation, test your applications and more. +- [Use agent mode in VS Code](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode) +- [GitHub Copilot Chat Cheat Sheet](https://docs.github.com/copilot/reference/github-copilot-chat-cheat-sheet) +- [Custom instructions](https://docs.github.com/copilot/how-tos/configure-custom-instructions/add-repository-instructions) \ No newline at end of file diff --git a/Using-GitHub-Copilot-with-JavaScript/images/activate-chat.png b/Using-GitHub-Copilot-with-JavaScript/images/activate-chat.png new file mode 100644 index 0000000..ed277ee Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/activate-chat.png differ diff --git a/Using-GitHub-Copilot-with-JavaScript/images/agent-mode.png b/Using-GitHub-Copilot-with-JavaScript/images/agent-mode.png new file mode 100644 index 0000000..91224f9 Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/agent-mode.png differ diff --git a/Using-GitHub-Copilot-with-JavaScript/images/explain-file.png b/Using-GitHub-Copilot-with-JavaScript/images/explain-file.png new file mode 100644 index 0000000..6c1029a Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/explain-file.png differ diff --git a/Using-GitHub-Copilot-with-JavaScript/images/ghost-text.png b/Using-GitHub-Copilot-with-JavaScript/images/ghost-text.png new file mode 100644 index 0000000..2eb1b26 Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/ghost-text.png differ diff --git a/Using-GitHub-Copilot-with-JavaScript/images/inline-edits.png b/Using-GitHub-Copilot-with-JavaScript/images/inline-edits.png new file mode 100644 index 0000000..a5cb06f Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/inline-edits.png differ diff --git a/Using-GitHub-Copilot-with-JavaScript/images/nes.png b/Using-GitHub-Copilot-with-JavaScript/images/nes.png new file mode 100644 index 0000000..b564992 Binary files /dev/null and b/Using-GitHub-Copilot-with-JavaScript/images/nes.png differ