One place for hosting & domains


      How To Create a Custom Source Plugin in Gatsby

      The author selected the Internet Archive to receive a donation as part of the Write for DOnations program.


      In building a website or application, often one of the most difficult tasks is pulling data from multiple sources and collating it into a uniform output. A common way to solve this is to use entirely different build systems for different parts of a site, but this sometimes adds complexity while making uniformity harder to achieve. This is where Gatsby, a data-driven Static Site Generator (SSG), can provide a solution.

      One of the core objectives of Gatsby is to solve this problem for developers, and source plugins are the main way it does so. A source plugin is a bundle of code that handles bringing data into the Gatsby ecosystem from a given source. Sources can be from the local filesystem as with Markdown files, databases, published data feeds, or even completely dynamic remote data sources such as APIs.

      In this tutorial, you will build your own custom source plugin to bring new data into Gatsby from a real-world API. You will also format the data so that it can be accessed throughout Gatsby, and by the end of the tutorial, have a working project that builds static HTML from your new dynamic data source.


      Before starting, here are a few things you will need:

      • A local installation of Node.js for running Gatsby and building your site. The installation procedure varies by operating system, but DigitalOcean has guides for Ubuntu 20.04 and macOS, and you can always find the latest release on the official Node.js download page.
      • Some familiarity with JavaScript, for working in Gatsby. The JavaScript language is an expansive topic, but a good starting spot is our How To Code in JavaScript series.
      • Some familiarity with web APIs, Node.js, and JSON.
      • A new Gatsby project, scaffolded from gatsby-starter-default. For satisfying this requirement and building a new Gatsby project from scratch, you can refer to Step 1 of the How To Set Up Your First Gatsby Website tutorial.
      • Some familiarity with React and JSX, as well as HTML elements, if you want to customize the user interface (UI) of your posts beyond what is covered in this tutorial.

      This tutorial was tested on Node.js v14.16.1, npm v6.14.12, Gatsby v3.13.0, and node-fetch v2.6.2.

      Step 1 — Scaffolding Files and Installing Dependencies

      When building something, the first step is always to get your tools and parts in order. In this step, you will put the initial building blocks of your source plugin in place by creating the necessary file structure and installing the dependencies your code will rely on.

      Since this will be a local plugin, create a directory within your Gatsby project to hold the source code of the plugin under a root-level plugins directory. You can do this by manually creating the folder in your file browser, or from the command line in the root of your project with the mkdir command:

      • mkdir -p plugins/my-custom-source-plugin

      Note: If you want to develop your plugin outside of your Gatsby project directory, you can do so, but it requires some extra steps to get Gatsby to pull the files into your site. For more on this, check out the official Gatsby documentation.

      Next, you need to create a package.json file to mark this directory as a Node.js package with its own dependencies. To create this file and pre-fill some required fields, use the following command:

      • cd plugins/my-custom-source-plugin
      • npm init -y

      This command navigates to your newly created plugin folder and then uses npm init to initialize a new package. The -y flag skips some questions that are irrelevant to this project and fills in the package.json file with the minimum required values.

      Now that package.json exists, you can add dependencies to your plugin that will make coding out functionality easier. Go ahead and install the only extra dependency you will be needing in this tutorial, node-fetch, by using the following command:

      • npm install node-fetch@^2

      Finally, create the gatsby-node.js file that will end up holding the main code of the source plugin:

      Note: If you are frequently building Gatsby plugins, you might find their plugin template helpful.

      Now that you have created the file structure to support your plugin and installed the initial dependencies, you will move on to giving instructions to Gatsby on how to find and load your plugin.

      Step 2 — Loading and Configuring the Plugin

      As is the case with any Gatsby plugin or theme, Gatsby has to be instructed on where and how to load the plugin from. To do this, you edit the main Gatsby config file gatsby-config.js , which resides in the root of your Gatsby project. Open the file in your editor of choice and add the following highlighted line:


      module.exports = {
        plugins: [
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,

      Because your plugin’s source code lives in the plugins directory, all that is required to get Gatsby to load it is to pass in the name of the sub-directory where it can be found within that folder. Your plugin also does not take any options at the moment, so there is no need to pass an options object to it in the Gatsby configuration block.

      Save gatsby-config.js and exit from the file.

      You have now configured Gatsby to load your custom source plugin, as well as told it exactly where to find the source code it should execute. In the next step, you will build out this source code to pull data into the Node.js runtime from your custom remote source.

      Step 3 — Pulling Raw Data Into Node.js

      In the previous step, you configured Gatsby to load and execute your custom source plugin’s code, but you still need to build out this code to accomplish the task of bringing new data into the Gatsby ecosystem. In this step, you will write the code that does this, fetching remote data via node-fetch and preparing it for use in future steps.

      Source plugins can pull data from almost anywhere, local or remote, but in this tutorial your source plugin will be specifically pulling titles and excerpts from the Computer Programming Books category in Wikipedia via their public API.

      Open your my-custom-source-plugin/gatsby-node.js file in your plugins directory and add the following code:


      const fetch = require('node-fetch').default
       * Fetch a list of computer books from Wikipedia, with excerpts
      async function getWikiProgrammingBooks() {
        const BASE_ENDPOINT = "";
        // Get list of books
        const listEndpoint = new URL(BASE_ENDPOINT);
        listEndpoint.searchParams.append('list', 'categorymembers');
        listEndpoint.searchParams.append("cmtitle", "Category:Computer_programming_books");
        listEndpoint.searchParams.append("cmlimit", "10");
        const listResults = await (await fetch(listEndpoint.toString())).json();
        // Extract out the page IDs from the list
        const pageIds = => listing.pageid);
        // Fetch details for page IDs
        const extractEndpoint = new URL(BASE_ENDPOINT);
        extractEndpoint.searchParams.append("pageids", pageIds.join("|"));
        extractEndpoint.searchParams.append("prop", "extracts|info");
        extractEndpoint.searchParams.append("exintro", "");
        extractEndpoint.searchParams.append("explaintext", "");
        extractEndpoint.searchParams.append("inprop", "url");
        const bookResult = await (await fetch(extractEndpoint.toString())).json();
        return Object.values(bookResult.query.pages);

      In this code, you have created a reusable function that can be called to return a list of computer programming books, along with their page IDs (a unique ID within Wikipedia) and excerpts/extracts. In the first part of the function, you build up the right API URL to use to fetch the initial list of titles and IDs belonging to a specific category (Computer Programming Books). The URL constructor and interface is used to make modifying the query string more readable and manageable.

      You use the fetch method from node-fetch to make a GET request to the constructed URL, which returns a list of the book titles with their IDs. That response is then turned into an array of just the pageid values, subsequently used to query the Wikipedia API again, this time requesting extracts and meta info generated for the given page ID. The page IDs are joined by the pipe character (|), as the Wikipedia API uses this format to accept multiple IDs through a single string value.

      Finally, since the results for page excerpts come back as an object with each book listing nested under its own ID as a key, you use Object.values() to omit the page ID key and convert the results into an array before returning them.

      If you were to log the output of this function, it would look something like this:

          "pageid": 379671,
          "ns": 0,
          "title": "The C Programming Language",
          "extract": "The C Programming Language (sometimes termed K&R, after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie...",
          "fullurl": "",

      Make sure to save your changes, but keep this file open as you will be adding more code to it in the next step.

      In this step you used node-fetch to retrieve remote source content and expose it within the gatsby-node.js file. In the next step, you will normalize the content as you use it to create new Gatsby nodes to use throughout the Gatsby project.

      Step 4 — Normalizing Data and Creating Nodes

      Fetching remote content and bringing it into gatsby-node.js in the previous step doesn’t mean that it is now accessible throughout Gatsby; in order to share data in a universal way, Gatsby uses the concept of nodes, which are shared across a unified GraphQL data layer. In this step, you will create these nodes, formatting your new content to match.

      Although you can now retrieve and access the results from Wikipedia by calling getWikiProgrammingBooks(), you still need to add the code to integrate this with Gatsby’s node system. In the same gatsby-node.js file from the previous step, add this new block of code to handle generating the nodes:


      const fetch = require('node-fetch').default
      exports.sourceNodes = async ({ actions, createContentDigest, createNodeId }) => {
        // Arbitrary node type constant
        const BOOK_TYPE = 'BookWikiPage';
        // Get books
        const bookResults = await getWikiProgrammingBooks();
        // Convert raw book results to nodes
        for (const book of bookResults) {
            id: createNodeId(`${BOOK_TYPE}-${book.pageid}`),
            parent: null,
            children: [],
            internal: {
              type: BOOK_TYPE,
              contentDigest: createContentDigest(book)

      In this code block, you are iterating over each book returned by getWikiProgrammingBooks and creating a Gatsby node for it via the createNode method. Each property and value passed into createNode has importance, and is worth consideration:

      • is used to spread the key-value pairs from your Wikipedia API object into the Gatsby node you are creating. This means that later on you can access node.title, as it will be copied from book.title.
      • id is a globally unique value within Gatsby. To make each book’s ID unique within your own plugin, you are combining the book type with the Wikipedia page ID to form an ID string. However, because you can’t be sure what IDs other plugins are using, you’ve used the best practice of passing your ID to createNodeId, which is a Gatsby helper function that ensures the ID is turned into something globally unique.
      • parent is a field that can be used to link your node to another via ID, marking this node as a child. Since each book is its own entity, unconnected to other nodes, you have left this as null, signifying it does not have a parent.
      • children is similar to parent as a way to link nodes, but takes an array of IDs. Since each book has no children, you have left the array empty.
      • internal is an object that groups together fields highly-specific to Gatsby’s internal node management system and other plugins. It can only contain official fields, which is why you did not spread the book object into it.
      • type is a globally unique string that describes the type of node you are creating, and will be used later when querying for nodes via GraphQL.
      • contentDigestis a hash string, which is built from the contents of the node and the Gatsby createContentDigest helper utility. This field helps Gatsby detect when a node has changed, as the hash string will change if any properties of the book object are modified.

      You have just added code that takes your source content and creates new Gatsby nodes with it, sharing them across the Gatsby environment. In the next step, you will verify that these nodes appear in the GraphQL data layer and can be queried.

      Step 5 — (Optional) Inspecting Node Output with the GraphQL API

      By now, you have pulled your source content into Gatsby and used it to create new nodes. As an alternative to manually debugging with breakpoints or log statements, in this step you will use the interactive GraphQL IDE to verify that these new nodes are being created and are able to be queried with the GraphQL API.

      Go ahead and start up your local development server by running this command from the root of your Gatsby project:

      Note: At the time of writing this tutorial, a problem with Gatsby’s dependency chain introduced an error that can return the message Error: Cannot find module 'gatsby-core-utils' when attempting to start the development server. If you encounter this error, run the following:

      • npm install gatsby-core-utils

      This will re-install the Gatsby core utilities and will resolve the dependency problem. For more information on this, check out the GitHub issue for this Gatsby error.

      In addition to launching a live version of your Gatsby site, the develop command also exposes a local GraphQL server and IDE. To verify that your code in gatsby-node.js is creating all the book nodes, you will use this GraphQL query to fetch the book titles, page IDs, and Gatsby IDs:

        allBookWikiPage {
          edges {
            node {

      To run this query, either open up the interactive GraphQL IDE at localhost:8000/___graphql and paste the query into the left side before executing, or query it via cURL:

      • curl --location --request POST 'http://localhost:8000/___graphql'
      • --header 'Content-Type: application/json'
      • --data-raw '{
      • "query": "{ allBookWikiPage { edges { node { title pageid id } } } }"
      • }'

      The response JSON will look something like this:

        "data": {
          "allBookWikiPage": {
            "edges": [
                "node": {
                  "title": "The C Programming Language",
                  "pageid": 379671,
                  "id": "818771ca-40aa-5cfd-b9e7-fddff093d5ec"
        "extensions": {}

      Having verified that your new custom source nodes have been created and are accessible in the GraphQL data layer, the next step is to use them to create visible content for visitors of your site or application.

      Step 6 — (Optional) Creating Pages Based on Nodes

      So far, all of the previous steps have been focused on creating internal Gatsby nodes, including the last step of verifying their creation and ability to be retrieved. However, these nodes are only visible to code running in your Gatsby project, not to visitors of your site or application. In this step, you will add a React page template file and wire it up to your nodes so that your source plugin content turns into actual public-facing webpages.

      There are multiple ways to create pages based on Gatsby nodes, but for this tutorial you will be using the File System Route API, which creates pages based on a special filename syntax.

      First, create an empty file in src/pages with a filename of {BookWikiPage.title}.js. The curly braces tell Gatsby that the filename is using the File System Route API, and inside the braces, BookWikiPage.title tells Gatsby to create a page for each unique book title. Note that you are no longer working on files within the plugins directory, but are now working inside of the main Gatsby project.

      Next, add code to that file that will take the book node and display it as a webpage:


      import { graphql } from "gatsby";
      import * as React from "react";
      import Layout from "../components/layout";
      import Seo from "../components/seo";
      export default function BookPageTemplate({ data: { bookWikiPage } }) {
        const { title, extract, fullurl } = bookWikiPage;
        return (
            <Seo title={title} />
            <i>This article uses material from the Wikipedia article <a href={fullurl} target="_blank" rel="noreferrer">"{title}"</a>, which is released under the <a href="">Creative Commons Attribution-Share-Alike License 3.0</a>.</i>
      export const pageQuery = graphql`
        query ($id: String!) {
          bookWikiPage(id: { eq: $id }) {

      At the end of your code is an exported variable called pageQuery, which uses the Gatsby GraphQL tag. Gatsby will evaluate the GraphQL query that follows it, passing the results to the BookPageTemplate function.

      The BookPageTemplate function, which is a React component, then takes the results of the GraphQL query and displays them as part of a web page by embedding the values into the JSX that it returns. The title of the book is used as the main heading and title of the page, the extract is displayed as a block quote, and a link to the full Wikipedia entry page is embedded at the bottom.

      You also mark the BookPageTemplate function as the default export by using export default before its declaration, as Gatsby expects to find the React component responsible for producing the final rendered page as the default export of each page template file.

      Having added the React template code to the file, save the changes and close it. Navigate to http://localhost:8000/the-c-programming-language/ to render a sample page:

      Screenshot showing a book listing page generated for

      Note: For a more manual approach to creating pages based on nodes, you can use the createPages API inside of gatsby-node.js.

      To display a listing of these new nodes and their associated pages, you will also create a dedicated listing page, which will display all the books in one location. Under src/pages, create a new file with the filename of books.js. Next, add the following code into it:


      import { graphql, Link } from "gatsby";
      import * as React from "react";
      import Layout from "../components/layout";
      import Seo from "../components/seo";
      export default function BookListingsPageTemplate({ data: { allBookWikiPage } }) {
        return (
            <Seo title="Programming Books Listing" />
            <p>Here are some computer programming books that have their own Wikipedia entries:</p>
            { => {
              const node = edge.node;
              return (
                <details key={node.title}>
                  <div className="details-body">
                    <div className="links">
                      <Link href={node.gatsbyPath}>Internal Page</Link>
                      <a rel="noreferrer" href={node.fullurl}>Wikipedia Page</a>
      export const pageQuery = graphql`
        query {
          allBookWikiPage {
            edges {
              node {
                gatsbyPath(filePath: "/{BookWikiPage.title}")

      Similar to the {BookWikiPage.title}.js page template, this file also uses the GraphQL pageQuery tag to pull in data from the GraphQL layer and pass it to a React component. However, while the previous template rendered a single book based on ID, this template will render a listing of all the books, while linking to the individual book pages created previously.

      Each book listing uses a <details> element, which enables the listing to expand to show the full excerpt of the book and links or to collapse to show just the title. Following best practices, you also pass a unique value to key while iterating through the array, using the Gatsby Link component for internal links and a tags for external links.

      The gatsbyPath(filePath: "/{BookWikiPage.title}") string in the GraphQL query uses the special gatsbyPath() function to retrieve the public path that will be created based on the File System Route API filename that is passed in.

      Save and exit from this file.

      Note: When changing data sources for components, the hot re-loading feature will sometimes return an error like the following: error Cannot query field "gatsbyPath" on type "BookWikiPage" graphql/template-strings. To fix this error, restart the development server manually by ending the process and running npm run develop again.

      With all the books on one page, even with collapsible sections things have gotten a little crowded, so the final step is to add some styling to make it easier for visitors to read the listing. Create a new stylesheet file at src/styles/books.css. You can do this in your file browser or with the command line from the root of your Gatsby project:

      • mkdir -p ./src/styles
      • touch ./src/styles/books.css

      Next, add the following CSS into the file:


      details {
        border: 1px dotted black;
        margin: 6px;
        padding: 6px;
      .details-body {
        background-color: #eedeff;
        margin: 4px 0px 2px 12px;
        padding: 4px;
        border-radius: 4px;
      .links {
        display: flex;
        justify-content: space-evenly;

      This CSS adds a border around each book listing, spacing and margins within the listing, and spacing between the internal and external book links. After adding the CSS into the file, save and close it before moving on.

      Finally, update the book listing page template to pull this CSS file in:


      import { graphql, Link } from "gatsby";
      import * as React from "react";
      import Layout from "../components/layout";
      import Seo from "../components/seo";
      import "../styles/books.css";

      Save and close this file with the newly added CSS import line.

      To see the results, run the develop command again to bring up the development server and preview the new pages:

      You can now access your book listing page at localhost:8000/books/.

      Screenshot showing the book listings page, using the template file in the tutorial. Each section can be expanded to show the excerpt and links or collapsed to show just the title.

      You have now not only built a Gatsby source plugin from scratch, but also used it to generate pages based on a React template.


      By following the steps in this tutorial, you have now finished building a custom source plugin that brings outside content into your Gatsby project and used it to power new pages within your site.

      There is a lot of depth to source plugins. If you are interested in following best practices and learning more advanced source plugin concepts, here are some areas that might interest you:

      If you would like to read more about Gatsby, check out the rest of the How To Create Static Web Sites with Gatsby.js series.

      Source link

      Comment utiliser Visual Studio Code pour le développement à distance via le plugin Remote-SSH


      Visual Studio Code est un environnement de développement intégré (IDE) populaire pour les développeurs. Son grand choix de plugins, sa conception minimale et son support cross-platform en font une solution idéale pour les développeurs de tous niveaux. Ce tutoriel met l’accent sur l’utilisation du plugin Remote-SSH pour activer le développement de logiciels à distance. Avec ce plugin, vous pouvez éditer des fichiers sur votre poste de travail local, mais aussi exécuter des tâches de développement telles que l’exécution de programmes, les tests unitaires ou l’analyse statique sur un serveur distant.

      Il existe de nombreuses raisons pour lesquelles cela peut vous être bénéfique. Par exemple, vous pouvez avoir un poste de travail Windows et vouloir développer sur Windows, mais votre code tournera au final sur Linux. Vous pouvez avoir besoin de davantage de mémoire vive ou de puissance de traitement que n’en possède votre machine actuelle, ou vous souhaitez maintenir le code à l’écart de votre machine personnelle en raison d’une politique d’entreprise, ou du désir de préserver votre poste de travail.

      Dans ce tutoriel, vous allez activer le plugin Remote-SSH, configurer Visual Studio Code pour exécuter le code sur le serveur distant, et exécuter le code de votre installation locale de Visual Studio Code sur le serveur distant.

      Conditions préalables

      Pour suivre ce guide, vous aurez besoin des éléments suivants :

      • Une machine de développement locale fonctionnant sous Windows, MacOSX ou Linux. Ce tutoriel ne fonctionnera pas sur les dispositifs ChromeOS.
      • Visual Studio Code, que vous pouvez télécharger et installer depuis le site web officiel.
      • Une paire de clés SSH générée :
      • Un serveur Ubuntu 18.04 configuré en suivant le guide de configuration initiale du serveur Ubuntu 18.04, comprenant un utilisateur non root sudo activé et un pare-feu.

      Étape 1 — Installation du plugin Remote-SSH

      Extensions Marketplace​​​ est l’endroit où vous pouvez télécharger les extensions prises en charge et les extensions tierces pour une variété d’outils et de langages de programmation différents. C’est là que vous allez rechercher le plugin Remote-SSH en vue de l’installer.

      Sur le côté gauche de l’IDE, il existe une rangée verticale de cinq icônes. L’icône du bas, qui ressemble à quatre carrés dans une boîte avec le carré supérieur droit qui explose, est l’icône d’Extensions Marketplace :

      Emplacement de l'icône Extensions Marketplace

      Vous pouvez également accéder à cette section en appuyant sur Ctrl+Shift+X. Lorsque vous ouvrirez cette page, vous verrez des suggestions de plugins à télécharger et à installer.

      Une fois que vous avez ouvert Extensions Marketplace, tapez Remote-SSH dans la barre de recherche d’Extensions Marketplace. Lorsque vous trouvez le plugin, sélectionnez-le et cliquez ensuite sur le bouton vert Install pour installer l’extension.

      Recherche du plugin Remote SSH

      L’extension est maintenant installée. Ensuite, vous allez configurer l’extension afin de pouvoir vous connecter à votre serveur.

      Étape 2 — Configuration du plugin Remote-SSH et connexion à votre serveur

      Maintenant que vous avez installé le plugin, vous pouvez le configurer pour vous connecter à un serveur. Pour ce faire, vous aurez besoin des éléments d’information suivants :

      • L’IP ou le nom d’hôte du serveur.
      • Le nom d’utilisateur avec lequel vous allez vous connecter.
      • La clé privée que vous utiliserez pour authentifier votre utilisateur.

      Vous utiliserez ces informations pour créer un fichier de configuration SSH que Visual Studio Code peut utiliser pour SSH vers le serveur afin de synchroniser les fichiers et d’exécuter le code en votre nom. Vous allez créer cette configuration en utilisant Visual Studio Code.

      Maintenant que vous avez installé le plugin Remote-SSH, vous verrez une petite boîte verte dans le coin en bas à gauche de l’interface Visual Studio Code. Si vous survolez la boîte avec le pointeur de votre souris, la fenêtre contextuelle indiquera Open a remote window. Le bouton ressemble à un signe “supérieur à” situé un peu au-dessous d’un signe “inférieur à” (><), comme l’illustre l’image suivante :

      Bouton vert de l'interface Open a remote window

      Cliquez sur le bouton, et une boîte de dialogue apparaît en haut, au centre. Sélectionnez Remote-SSH : Open Configuration File… dans la liste :

      Selecting Configure SSH in the UI

      L’invite suivante vous demandera quel fichier de configuration vous voulez ouvrir. Si vous êtes sous Windows, vous verrez deux emplacements : un dans votre répertoire utilisateur personnel, et un dans l’emplacement d’installation pour SSH. Vous devez utiliser le fichier dans votre répertoire utilisateur lors de la configuration du serveur.

      Sélectionnez le fichier et votre éditeur ouvrira le fichier config. Ajoutez le code suivant au fichier pour définir la connexion à votre serveur, en remplaçant les sections surlignées par les informations de votre serveur :


      Host my_remote_server
          HostName your_server_ip_or_hostname
          User sammy
          IdentityFile /location/of/your/private/key

      Voici comment fonctionne ce fichier de configuration :

      • Host : spécifie un nom pour votre hôte. Cela vous permet d’utiliser un nom ou abrégé au lieu de l’adresse IP complète ou du nom d’hôte lors de la connexion au serveur.
      • HostName : le nom d’hôte réel du serveur, qui est soit une adresse IP, soit un nom de domaine entièrement qualifié.
      • User : l’utilisateur que vous voulez utiliser pour vous connecter.
      • IdentityFile: : le chemin vers votre clé privée SSH. Sur les systèmes Mac et Linux, vous le trouverez dans votre répertoire personnel, dans un répertoire .ssh caché, généralement appelé id_rsa. Si vous êtes sous Windows, vous avez spécifié un emplacement pour enregistrer ce fichier lorsque vous l’avez créé en utilisant putty-gen.

      Spécifiez les valeurs appropriées dans votre fichier et enregistrez le fichier.

      Visual Studio Code est maintenant configuré et prêt à vous connecter à votre serveur. Cliquez sur le bouton vert Open a remote window​​​​​​ dans le coin inférieur gauche et sélectionnez Remote-SSH : Connect to Host…

      Connexion au serveur depuis Visual Studio Code

      Une fois que vous avez fait tout cela, les serveurs disponibles et configurés apparaîtront dans le menu déroulant. Sélectionner le serveur auquel vous voulez vous connecter à partir de cette liste.

      Si c’est la première fois que vous vous connectez à ce serveur depuis votre machine, vous serez probablement invité à utiliser la boîte de dialogue de vérification des empreintes digitales SSH, comme celle qui figure dans l’image suivante :

      Confirmer votre empreinte digitale SSH

      Cela permet de s’assurer que vous vous connectez réellement au serveur auquel vous pensez. Vous pouvez le vérifier en vous connectant manuellement à votre serveur et en exécutant ssh-keygen -l -f /etc/ssh/ pour visualiser l’empreinte digitale du serveur. Si cette empreinte digitale est la même que celle qui vous est présentée dans Visual Studio Code, alors vous vous connectez effectivement au serveur auquel vous pensez, vous pouvez donc cliquer sur Continue.

      Visual Studio Code ouvre par défaut une nouvelle fenêtre lorsqu’une nouvelle connexion est établie. Une nouvelle fenêtre apparaîtra avec l’écran d’accueil. Vous saurez que votre connexion a réussi si vous voyez SSH : your_ip_address_or_hostname dans la boîte verte, située dans le coin inférieur gauche. Cela signifie que Visual Studio Code est connecté et communique avec votre serveur distant.

      Connexion SSH réussie

      Maintenant que vous êtes connecté, vous pouvez exécuter des commandes et du code à partir de votre éditeur.

      Étape 3 — Exécution de code sur le serveur distant

      Le plugin Remote-SSH est configuré, et il est temps d’exécuter du code sur votre machine distante. Ouvrez une fenêtre de terminal en sélectionnant Terminal dans la barre de navigation en haut de la fenêtre Visual Studio et en cliquant sur New Terminal. Vous pouvez également ouvrir un terminal en appuyant sur CTRL+Shift+`. Le terminal qui est ouvert est un terminal sur votre serveur distant, et non un terminal sur votre machine locale.

      Lorsque le terminal s’ouvre, lancez la commande suivante pour afficher l’adresse IP de votre serveur afin de vérifier que vous êtes connecté à votre serveur distant :

      Vous verrez la sortie suivante dans votre terminal :


      1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 link/ether 16:cb:05:5b:30:f1 brd ff:ff:ff:ff:ff:ff inet your_server_ip brd your_broadcast_address scope global eth0 valid_lft forever preferred_lft forever ...

      Pour tester la capacité d’exécution de code distant, créez un nouveau fichier Python appelé dans votre éditeur. Lorsque vous êtes connecté à votre serveur distant, tous les fichiers créés par Visual Studio Code sont enregistrés sur ce serveur, et non sur votre machine locale.

      Ajoutez le contenu suivant au fichier :

      print("Hello Sammy!")

      Pour exécuter ce programme sur votre serveur, ouvrez un terminal dans Visual Studio Code à partir du menu navigation ou en appuyant sur la séquence de touches CTRL+Shift+`. Comme cette session de terminal est connectée à votre serveur distant, exécutez la commande suivante dans le terminal pour exécuter votre programme :

      La sortie de votre programme sera affichée.

      Exécuter votre script Python

      Vous pouvez également exécuter le fichier à partir du menu contextuel Debug en sélectionnant Run without Debugging.

      Remarque : Si vous avez des extensions de développement installées dans Visual Studio Code, telle que l’extension Python, vous devrez réinstaller ces extensions sur votre serveur via Extensions Marketplace. Si vous avez déjà installé ces plugins dans Visual Studio Code, lorsque vous les recherchez à nouveau, le Marketplace indiquera Install on SSH: hostname. Faites toujours attention au contexte de développement dans lequel vous vous trouvez, car c’est là que Visual Studio Code installera vos plugins et créera vos fichiers. Si vous essayez d’exécuter votre code sans que ces plugins soient installés, des boîtes de dialogue d’erreur apparaîtront dans le coin inférieur droit de l’écran, vous invitant à les installer sur votre serveur distant. Une fois que vous les aurez installés, vous devrez probablement recharger Visual Studio Code. Lorsque vous le relancerez, il continuera à fonctionner sur le serveur distant sans que vous ayez à vous reconnecter manuellement.


      Le code Visual Studio est maintenant configuré pour le développement sur un serveur distant utilisant SSH. L’exécution à distance avec un IDE offre de nombreux avantages, notamment la possibilité de tester rapidement le fonctionnement de votre code sur différents systèmes d’exploitation et pour différentes spécifications matérielles. Tant que vous disposez d’une connexion Internet, vous pouvez vous connecter à votre serveur et travailler sur votre code depuis n’importe quel ordinateur, et vous pourrez développer en utilisant un environnement Linux même si vous utilisez Windows comme système d’exploitation principal.

      Source link

      Como usar o Visual Studio Code para o desenvolvimento remoto por meio do plug-in Remote-SSH


      O Visual Studio Code é um Ambiente integrado de desenvolvimento (IDE) para desenvolvedores. Sua grande seleção de plug-ins, de design mínimo e suporte multiplataforma tornam-no uma ótima escolha para os desenvolvedores de todos os níveis. Este tutorial se concentra no uso do plug-in Remote-SSH para habilitar o desenvolvimento de softwares remotos. Com esse plug-in , você pode editar arquivos na sua estação de trabalho local, mas executar tarefas de desenvolvimento, como a execução do programa, testes de unidade ou análise estática, em um servidor remoto.

      Há muitas razões para que isso seja benéfico para você. Por exemplo, você pode ter uma estação de trabalho Windows e querer desenvolver no Windows, mas seu código acabará sendo executado no Linux. Você pode precisar de mais RAM ou poder de processamento do que sua máquina atual tem disponível, ou querer manter o código fora da sua máquina pessoal devido a uma política de empresa ou pela vontade de manter sua estação de trabalho inalterada.

      Neste tutorial, você irá habilitar o plug-in Remote-SSH, configurar o Visual Studio Code para executar o código no servidor remoto e executar o código de sua instalação local do Visual Studio Code no servidor remoto.


      Para acompanhar este guia, você vai precisar do seguinte:

      • Uma máquina local de desenvolvimento executando o Windows, MacOSX ou Linux. Este tutorial não funcionará nos dispositivos ChromeOS.
      • O Visual Studio Code, que pode ser baixado e instalado no site oficial.
      • Um par de chaves SSH gerado:
      • Um servidor Ubuntu 18.04 configurado conforme o Guia de configuração inicial do servidor Ubuntu 18.04, incluindo um usuário não raiz habilitado para o sudo e um firewall.

      Passo 1 — Instalando o plug-in Remote-SSH

      O Marketplace de extensões é o local onde pode você pode baixar extensões compatíveis e de terceiros para uma variedade de ferramentas e linguagens de programação diferentes. É aqui que você procurará pelo plug-in Remote-SSH e o instalará

      No lado esquerdo da IDE, há uma linha vertical de cinco ícones. O ícone mais abaixo, que se parece com quatro quadrados em uma caixa, estando o do topo direito descolando, é o ícone para o Marketplace de extensões:

      Localização do ícone do Marketplace de extensões

      Você também pode acessar essa seção pressionando Ctrl+Shift+X. Quando a página for aberta, você verá os plug-ins sugeridos para baixar e instalar.

      Assim que tiver o Marketplace de extensões aberto, digite Remote-SSH na barra de busca Search Extensions in Marketplace. Quando encontrar o plug-in, selecione-o e, em seguida, clique no botão verde Install para instalar a extensão.

      Procurando pelo plug-in Remote-SSH

      A extensão agora está instalada. Em seguida, você configurará a extensão para que você consiga conectar-se ao seu servidor.

      Passo 2 — Configurando o plug-in Remote-SSH e conectando-se ao seu servidor

      Agora que o plug-in está instalado, você pode configurá-lo para que se conecte a um servidor. Para fazer isso, serão necessárias as seguintes informações:

      • O IP ou nome do host do servidor.
      • O nome de usuário com o qual você se conectará.
      • A chave privada que você usará para autenticar seu usuário.

      Você usará essas informações para criar um arquivo de configuração SSH, que o Visual Studio Code pode usufruir para usar o SSH no servidor para sincronizar os arquivos e executar códigos em seu nome. Essa configuração será criada usando o Visual Studio Code.

      Agora que você tem o plug-in Remote-SSH instalado, verá uma pequena caixa verde no canto inferior esquerdo da interface do Visual Studio Code. Se você passar o ponteiro do mouse pela caixa, o pop-up dirá Open a remote window (Abrir uma janela remota). O botão se parece com um sinal “maior que” abaixo de um sinal “menor que” ><, como o da seguinte imagem:

      Botão de UI verde para abrir uma janela remota

      Clique no botão e uma caixa de diálogo aparece no centro superior. Selecione Remote-SSH: Open Configuration File… da lista:

      Selecionando configurar SSH na UI

      O próximo prompt perguntará qual arquivo de configuração você deseja abrir. Se estiver no Windows, verá duas localizações: uma no seu diretório de usuário pessoal e outra na localização de instalação para o SSH. Você deve utilizar o arquivo no seu diretório de usuário enquanto estiver configurando o servidor.

      Selecione o arquivo e seu editor abrirá o arquivo config. Adicione o código a seguir ao arquivo para definir a conexão com seu servidor, substituindo as seções destacadas pelas informações do seu servidor:


      Host my_remote_server
          HostName your_server_ip_or_hostname
          User sammy
          IdentityFile /location/of/your/private/key

      Aqui está como este arquivo de configuração funciona:

      • Host: especifica um nome para seu host. Isso permite que você use como alternativa um nome curto ou uma abreviação, em vez do endereço IP completo ou nome do host ao se conectar ao servidor.
      • HostName: o nome real do host do servidor, que é um endereço IP ou um nome de domínio totalmente qualificado.
      • User: o usuário com o qual você deseja se conectar.
      • IdentityFile: o caminho para sua chave SSH privada. Em sistemas Mac e Linux, você encontrará isso em seu diretório base, em um diretório .ssh escondido, chamado normalmente de id_rsa. Se estiver no Windows, você terá especificado um local para salvar este arquivo quando o criou usando o putty-gen.

      Especifique os valores apropriados no seu arquivo e salve o arquivo.

      O Visual Studio Code está agora configurado e pronto para se conectar ao seu servidor. Clique no botão verde Open a remote window, no canto inferior esquerdo e selecione Remote-SSH: Connect to Host…

      Conectando-se ao servidor através do Visual Studio Code

      Assim que tiver feito isso, todos os servidores disponíveis e configurados aparecerão no menu suspenso. Selecione o servidor ao qual você deseja se conectar dessa lista.

      Se essa é a primeira vez que você se conecta a este servidor de sua máquina, provavelmente será exibido um diálogo de verificação do SSH Fingerprint, como a da seguinte imagem:

      Confirmando seu SSH Fingerprint

      Isso é para garantir que você esteja se conectando ao servidor correto. É possível verificar isso fazendo login manualmente e executando ssh-keygen -l -f /etc/ssh/ para visualizar as impressões digitais do servidor. Se essa impressão for a mesma que aquela sendo apresentada a você no Visual Studio Code, então você de fato está se conectando ao servidor correto, logo, clique em Continue.

      Por padrão, o Visual Studio Code abre uma nova janela quando uma nova conexão é feita. Uma nova janela aparecerá com a tela de boas-vindas. Você saberá se sua conexão foi bem-sucedida caso veja SSH: your_ip_address_or_hostname na caixa verde no canto inferior esquerdo. Isso significa que o Visual Studio Code está conectado e se comunicando com seu servidor remoto.

      Conexão SSH bem-sucedida

      Agora que está conectado, execute comandos e códigos do seu editor.

      Passo 3 — Executando códigos no servidor remoto

      O plug-in Remote-SSH está configurado e é hora de executar algum código em sua máquina remota. Abra uma janela de terminal selecionando Terminal da barra de navegação no topo da janela do Visual Studio e clicando em New Terminal. Também é possível abrir um terminal pressionando CTRL+Shift+`. O terminal que é aberto é um terminal no seu servidor remoto, não um na sua máquina local.

      Quando o terminal abrir, emita o seguinte comando para visualizar o endereço IP do seu servidor para verificar se você está conectado ao seu servidor remoto:

      Você verá o seguinte resultado no seu terminal:


      1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 link/ether 16:cb:05:5b:30:f1 brd ff:ff:ff:ff:ff:ff inet your_server_ip brd your_broadcast_address scope global eth0 valid_lft forever preferred_lft forever ...

      Para testar a capacidade de executar códigos remotos, crie um novo arquivo do Python chamado no seu editor. Quando estiver conectado ao seu servidor remoto, todos os arquivos criados através do Visual Studio Code serão salvos no servidor, não na sua máquina local.

      Adicione o conteúdo a seguir ao arquivo:

      print("Hello Sammy!")

      Para executar este programa no seu servidor, abra um terminal no Visual Studio Code por meio do menu de navegação ou pressionando a sequência de teclas CTRL+Shift+`. Como essa sessão de terminal está conectada ao seu servidor remoto, execute o seguinte comando no terminal para executar seu programa

      O resultado do seu programa será exibido.

      Executando seu script em Python

      Também é possível executar o arquivo a partir do menu de contexto Debug, selecionando Run without Debugging.

      Nota: caso tenha qualquer extensão de desenvolvimento instalada no Visual Studio Code, como a extensão do Python, será necessário reinstalar essas extensões no seu servidor através do Marketplace de extensões. Caso já tenha instalado previamente esses plug-ins no Visual Studio Code, quando for procurar por eles novamente, o Marketplace dirá Install on SSH: hostname. Sempre tenha cuidado sobre qual o contexto de desenvolvimento em que você está, pois é aqui onde o Visual Studio Code instalará seus plug-ins e criará seus arquivos. Se tentar executar seu código sem esses plug-ins instalados, caixas de diálogo de erro aparecerão no canto inferior direito da tela, solicitando pela instalação deles no seu servidor remoto. Depois de instalá-los, eles provavelmente exigirão que você recarregue o Visual Studio Code. Quando você reiniciá-lo, ele continuará funcionando no servidor remoto, sem que você tenha que se reconectar manualmente.


      Agora, você tem o Visual Studio Code configurado para o desenvolvimento em um servidor remoto usando o SSH. A execução remota com uma IDE traz muitos benefícios, incluindo a capacidade de testar rapidamente como seu código é executado em diferentes sistemas operacionais e diferentes especificações de hardware. Enquanto tiver uma conexão de Internet, você pode se conectar ao seu servidor e trabalhar em seu código de qualquer computador e será capaz de desenvolver usando um ambiente Linux, mesmo se estiver usando o Windows como seu sistema operacional primário.

      Source link