One place for hosting & domains

      Studio

      How To Develop a Docker Application on Windows using WSL, Visual Studio Code, and Docker Desktop


      Introduction

      The advent of the Windows Subsystem for Linux 2 (WSL 2 or WSL for short) has simplified Linux-based development on Windows. The WSL 2 allows for direct integration with Docker Desktop and has plugins for direct development using Visual Studio Code.

      In this tutorial you’ll set up a development environment on Windows using Visual Studio Code, the WSL, and Docker Desktop. You’ll build a Python Flask web service in Docker to demonstrate the development functionality of these tools.

      Prerequisites

      In order to follow along with this guide, you’ll need:

      • Personal Computer with Windows 10 and the WSL 2 installed: You’ll want to ensure that the WSL is installed correctly and that you have Ubuntu 20.04 installed into the WSL. You can follow the tutorial How To Install the Windows Subsystem for Linux 2 on Microsoft Windows 10 to set this up.

      • VSCode Installed: You can download and install VSCode from its official website. You do not need to worry about installing plugins. The required plugins will be discussed in this tutorial.

      Step 1 — Installing Docker Desktop and Connecting to the WSL

      Docker is a common development tool used by developers to deploy applications. Docker Desktop has the advantage of also being able to run and integrate with your WSL Linux environments.

      Set up Docker by downloading Docker Desktop from Docker’s website and clicking the Get Docker button to start the download.

      Go to Docker's website and download Docker Desktop

      Run the executable once you get it downloaded and allow it to make changes.

      Run the executable and let Docker make changes

      During the installation make sure that Install required Windows components for WSL 2 is checked. Whether or not you want a Desktop icon is up to you.

      Make sure that

      After the installation process is done you’ll be prompted to log out and back in for your changes to take effect. Click on the Close button and then make sure to log out and back in so that the changes take effect.

      Once Docker is done installing you'll need to logout and log back in for changes to take effect

      Log back in and launch Docker Desktop from the Start menu.

      Launch Docker Desktop from the start menu

      Warning: When you first launch Docker it will prompt you with a Docker tutorial.

      Docker Tutorial Launched

      If you are unfamiliar with Docker it may be worth your time to do the Docker tutorial, but it is not required for this current tutorial. Once you have either done the tutorial or skipped it, continue on.

      The Docker dashboard will show up. This is where any running containers will appear as well as settings and status of Docker. If you see the logo is green in the bottom left corner that means that Docker is running. If it is yellow then Docker Desktop is still starting; give it a minute or so to finish. If the indicator is red, then Docker is unable to start.

      The Docker dashboard will open. If the logo in the bottom left is green it means Docker is running

      Next you’ll need to expose Docker to the WSL so you can run Docker on your Ubuntu environment. Click on the Gear icon in the top right corner to open Settings. From there you’ll click the Resource tab and then click WSL Integration. You’ll see your Ubuntu environment there, but toggled off, along with any other WSL environments you may have installed.

      Go to Settings, select Resources, and select WSL Integration. You'll see your WSL Ubuntu there, not selected

      Enable Docker in your Ubuntu environment by clicking on the slider to turn it on, and then click Apply & Restart. Once the restart is done your Ubuntu environment will have access to Docker.

      Select your WSL Ubuntu and click Apply & Restart

      Now you can test your Docker connectivity with the WSL. Open a terminal to the operating system you enabled Docker in, Ubuntu in this case, and run the Docker hello world command:

      Your Ubuntu environment should download and run the hello world container and display its output.

      Test Docker by running Docker run hello-world in your WSL Ubuntu

      Now that you have Docker connected to the WSL you’ll learn how to develop within the WSL directly using Visual Studio Code and the Remote Development Extension.

      Step 2 — Using Visual Studio Code’s Remote Extension to Develop within the WSL

      You can integrate your WSL Ubuntu environment with your Visual Studio Code, henceforth known as VSCode, to be able to develop directly in a Linux environment.

      First, open VSCode. Go to the Extensions tab on the left hand side of the window. Search for Remote - WSL and the Remote - WSL extension will appear. Click on it and click Install to install it.

      Open VSCode, go to Extensions and search for Remote. Install the Remote - WSL Extension

      Once the installation is completed, press CTRL + Shift + P to open the VSCode command dialog. Type Remote-WSL and you’ll see a few options appear. You can open a new WSL environment, open an existing folder, etc. Select Remote-WSL: New WSL Window. This will open a new VSCode window connected to the Ubuntu WSL environment.

      Press CTRL + Shift + P to open the VSCode command dialog and type Remote. You'll see WSL there. Select Remote-WSL: New WSL Window

      Now that you’re in this new window you can press CTRL + Shift + ` or by clicking on Terminal -> New Terminal in the navigation bar to open up a new terminal and you’ll be dropped into the WSL terminal. Any file you create will be stored in the WSL filesystem as well.

      If you open a new terminal you'll open your Ubuntu terminal and be able to develop using VSCode directly in the WSL

      Now that you have your development environment set up, you’ll build a Python microservice using the Flask framework that creates a 301 redirect to a site that you specify as an environment variable and package it within a Docker container.

      Step 3 — Setting Up Your Developer Environment

      First you’ll want to set up a development environment so you can develop your code using Visual Studio Code. Navigate to the sidebar on the left hand side and click on the topmost icon that looks like a sheet of paper. You will be prompted to either Open a Folder or Clone a Repository.

      File explorer dialog box open

      From here select Open a Folder. The default location will be your home directory. Select this option and click OK.

      Open home directory

      You may be prompted by Visual Studio Code asking if you trust the authors of this folder. This is a security measure to ensure that no automatically executed code can harm your PC. In this case, everything is good so select Yes, I trust the authors.

      Author Trust Dialog box

      Now you should see your home directory in the file explorer panel to the left. Next, create a directory to store your project. Navigate to the folder icon with a plus symbol. When you hover over the icon a popup should appear saying New Folder. Click on this icon to create a new folder and name it my-app. A new empty directory should appear in the explorer to the right.

      New Folder Icon
      You now have your developer environment set up and ready to build your Python microservice in the next step.

      Step 4 — Creating a Python Virtual Environment for Your Project

      Before you get started coding, you need to set up your Python developer environment. In this step, you will install and activate your Python requirements within a virtual environment for easier management.

      You can do all of this from within the terminal in Visual Studio Code. Press the CTRL + Shift + ` key combo to open a new terminal or click on New Terminal under the Terminal section in the top navigation bar. Once you’ve done this you should see a new terminal appear at the bottom of the Visual Studio Code window.

      New terminal in Visual Studio Code

      From this terminal navigate into the directory you created for you code, my-app.

      Next, install the python3-venv Ubuntu package so you can create Python virtual environments.

      • sudo apt update && sudo apt install python3-venv

      Now create your virtual environment using Python:

      This will create a directory called myapp in your current directory. Inside, it will install a local version of Python and a local version of pip, the package manager for Python. You can use this to install and configure an isolated Python environment for your project.

      Before you install your project’s Python requirements, activate the virtual environment:

      • source myapp/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (myapp)user@host:~/my-app$.

      With your virtual environment active, install flask and gunicorn with the local instance of pip:

      • pip install flask gunicorn

      Note: Once you have activate your virtual environment (when your prompt has (myapp) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      Now that you have the packages installed, you will need to save this requirement and its dependencies. This is good practice so you can recreate your developer environment as needed and will aid in installing the correct packages into your Dockerfile in a later step.

      Use pip to save your environment’s information to a requirements.txt file:

      • pip freeze > requirements.txt

      Now that you have a working virtual environment for development, let’s build the microservice.

      Step 5 — Building a Python Microservice to Redirect Traffic

      The first thing you’ll need to do is create a Python file named app.py and a Dockerfile to specify your Docker requirements. You can create files via the terminal with the touch command and then refreshing the explorer:

      You can also use the file explorer to create a new file by clicking on your my-app folder, then clicking on the New File icon that looks like a piece of paper with a plus sign, then typing out the full name and extension of the file.

      Create your app.py

      Use either method to create app.py and Dockerfile.

      Once you’ve done this, open app.py. The microservice you are going to write today will have only one endpoint, as defined by the @app.route("/") decorator. This endpoint will use the redirect method within the Flask library to perform a 301 redirect to a site that is specified in an environment variable. If no environment variable is set, the app will redirect to DigitalOcean’s website by default.

      Open app.py by clicking on it and add the following lines of code.

      Add an import statement to import the os package, which will enable the microservice to read the environment variable you’ll define later:

      import os
      

      Next, import the Flask class and redirect function from the flask library. You’ll use these to set up your web framework and to redirect traffic to another site.

      from flask import Flask,redirect
      

      Next, create a Flask object that can be acted upon within the code. This is the instance of your web app that you will register routes to.

      app = Flask(__name__)
      

      Create a single method at the / route. You’ll use your Flask instance to decorate the function to specify the route. Within the function, you will use the Flask redirect function to perform a 301 redirect to another site that will be read from an environment variable. If the environment variable is not found, your app will default redirect to DigitalOcean’s home page. This is to ensure your app doesn’t crash if you forget to set an environment variable.

      @app.route('/')
      def hello():
          # Attempt to read REDIRECT_TO from the environment. If nothing is set
          # perform a 301 redirect to DigitalOcean's website
          return redirect(os.environ.get("REDIRECT_TO", "https://www.digitalocean.com"), code=301)
      

      Finally, create a main function that runs your Flask app externally on port 8080. The address 0.0.0.0 is used to designate that you want your app to run on the externally facing network interface of your device, not the local loopback device, also known as localhost.

      if __name__ == '__main__':
          app.run(host="0.0.0.0", port=8080)
      

      The finished app.py can be found below:

      # Import the os package to read the environment variable
      import os
      
      # Import the Flask class and redirect function from the flask library
      from flask import Flask,redirect
      
      
      # Create a Flask object to be acted upon
      app = Flask(__name__)
      
      # Python decorator that specifies the web route that will execute the code below
      @app.route('/')
      def hello():
          # Attempt to read REDIRECT_TO from the environment. If nothing is set
          # perform a 301 redirect to DigitalOcean's website
          return redirect(os.environ.get("REDIRECT_TO", "https://www.digitalocean.com"), code=301)
      
      # Main function that executes the Flask app
      if __name__ == '__main__':
          app.run(host="0.0.0.0", port=8080)
      

      Once you are done, save the file as app.py.

      Now that your app is written, let’s test it.

      Step 6 — Testing Your Microservice

      Now that your app is written, it is time to test it. In the terminal you opened in Visual Studio Code with the activated virtual environment, run the command:

      You should see Flask output that looks similar to this:

      Output

      * Serving Flask app 'app' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead * Debug mode: off * Running on all addresses. * WARNING: This is a development server. Do not use it in a production deployment. * Running on https://256.333.112.1:8080/ (Press CTRL+C to quit)

      This means that your Flask app is running. Open a browser and navigate to localhost:8080. When you do you should see output happen in your terminal and be redirected to DigitalOcean’s website. This is because you have not specified anywhere for your Flask app to redirect to, so it is using the default.

      To stop your Flask app, click in the Visual Studio Code window to ensure it is active and then press CTRL+C. You’ll see the prompt stop and you’ll be presented with your terminal again.

      Next, run the following command to set your redirect to something else.

      • REDIRECT_TO="https://digitalocean.com/community/tutorials"

      Run your Flask app again using the command

      Go to your browser again and navigate to localhost:8080. You should then be directed to the DigitalOcean tutorials page.

      Note: If you plan on testing multiples redirects with the same container, you may want to use a form of incognito mode. Most modern browsers will cache a 301 redirect, so if you change the environment variable, you may end up at the same site and not see your changes reflected. Using an incognito window or clearing your cache will help with this.

      With this, your app is done and is ready to be built into a Docker image.

      Step 7 — Building and Running Your Microservice in Docker

      In this final step you’re going to package your Python app as a microservice using Docker and a Dockerfile. A Dockerfile is a list of build commands that Docker uses to create your image. These can be commands to install packages, copy files, and more.

      Open the Dockerfile you created in a previous step so you can edit it. In this file you’re going to specify the base image, tell Docker where you want the code to run, create an environment variable that holds the redirect target, copy over all the necessary files to the Docker image, install the necessary Python packages, and finally add the command that will be executed when the container is run.

      Add the following code to Dockerfile to do this.

      First, you need to specify the base image you want to use. The python base image will contain the latest version of Python.

      FROM python 
      

      Next, set your working directory. This is the default directory that Docker will run commands in and drop you into if you connect with ssh.

      WORKDIR /var/www/
      

      Set the REDIRECT_TO environment variable to the default location you want to redirect to. Here I’m setting it to DigitalOcean’s Community Tutorial site. This can be changed when you run the image via the command line.

      ENV REDIRECT_TO=https://digitalocean.com/community/tutorials
      

      Copy your app.py and requirements.txt into your Docker container, using fully qualified paths for the destination.

      COPY ./app.py /var/www/app.py
      COPY ./requirements.txt /var/www/requirements.txt
      

      Run the necessary command to install the Python library requirements within your Docker image.

      RUN pip install -r /var/www/requirements.txt
      

      Finally, set the image run command to run your app. This is the command that is run whenever anyone tries to run your Docker container.

      CMD python3 app.py
      

      The complete Dockerfile is listed below.

      # Choose your base image
      FROM python 
      
      # Set your working directory
      WORKDIR /var/www/
      
      # Set environment variable for redirect. Can be overwritten by Docker run command
      ENV REDIRECT_TO=https://digitalocean.com/community/tutorials
      
      # Copy the necessary files
      COPY ./app.py /var/www/app.py
      COPY ./requirements.txt /var/www/requirements.txt
      
      # Install the necessary packages
      RUN pip install -r /var/www/requirements.txt
      
      # Run the app
      CMD python3 app.py
      

      When you are done, save the file.

      Now you can build the Docker image locally for testing. Run the following command to build your image and tag it with the name myapp. The -t option applies the tag to the Docker image:

      Finally, it’s time to test your Docker image. In your Dockerfile above you set an environment variable REDIRECT_TO to point at a website. This will overwrite the default value in your code so when you run this container, whatever site you specified in the Dockerfile will be your new location.

      Note: If you are prompted by windows to grant permission to Docker to access the network, click Allow.

      To test your image, run the following command:

      • docker run -p 8080:8080 myapp

      While your image is running, navigate to a browser and type localhost:8080 in the navigation bar and you should be redirected to the site listed in the Dockerfile.

      Warning: Sometimes the WSL terminal doesn’t recognize CTRL + C as a way to stop your Docker image. In this instance you’ll need to open another terminal and search for your running Docker image using the command:

      This will show an output similar to this:

      Output

      CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3f081712283e myapp "/bin/sh -c 'python3…" About a minute ago Up About a minute 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp reverent_saha

      Take the container id, which in this example is 3f081712283e and use the docker kill command to stop it.

      Finally, let’s test changing the environment variable of the redirect in the docker run command.

      Type the following command to change the environment variable to the DigitalOcean cloud console page, https://cloud.digitalocean.com.

      • docker run -p 8080:8080 -e REDIRECT_TO=https://cloud.digitalocean.com myapp

      Now if you go to a browser and browse to localhost:8080 you will be redirected to the site specified on the command line.

      Conclusion

      You have successfully set up a developer environment on Windows using the WSL, Visual Studio Code, and Docker Desktop. You’ve demonstrated how to build, test, and package code on Windows, allowing you to have more options when it comes to developer environments.



      Source link

      How To Set Up Visual Studio Code (VS Code) for PHP Development


      Introduction

      Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems.

      With a large collection of extensions for many programming languages, VS Code can be customized to serve a wide variety of development needs. In this guide, you’ll learn how to set up Visual Studio Code for working on PHP projects.

      The gif shows the VS Code interface for PHP development

      Prerequisites

      To follow this guide, you’ll need to download and install the appropriate version of Visual Studio Code for your operating system.

      The instructions in this guide were validated on an Ubuntu 20.04 desktop computer, but they should work seamlessly in all operating systems that are supported by VS Code. Please note, though, that keyboard shortcut keys may need to be slightly modified for compatibility with MacOS systems.

      Right after installation, VS Code already recognizes PHP code and helps with syntax highlighting, basic debugging, and code indentation. These features are suitable for quick edits or when working with individual PHP scripts. Working in larger projects, though, can become difficult without more context around the code and how each file interacts and integrates within the larger project.

      There are a number of VS Code extensions that can help speed up your productivity when working on PHP projects. In this guide, we’ll install and set up PHP Intelephense, a popular PHP extension for VS Code that provides several advanced features such as improved code completion, better navigation between components, rich information tooltips on mouse hover, code auto formatting, and real time error reporting based on static code analysis.

      Open the extensions tab by clicking on the last icon on the left menu bar, or by pressing CTRL + SHIFT + X. This will bring up a sidebar menu with a search box and a list of popular or recommended extensions. Type “php” or “intelephense” to locate the PHP Intelephense extension. Click on the Install button to install and enable the extension.

      The gif shows how to access the extensions menu on the left sidebar

      Once installation is complete, Intelephense’s official documentation recommends that you disable the built-in PHP Language Features extension that comes with VS Code.

      To disable this extension, type @builtin php in the Extensions search box to locate the built-in PHP extensions. Then click on the settings icon for the PHP Language Features extension, and click the Disable option in the drop-down menu.

      The gif shows how to disable the builtin PHP Language Features extension

      If you have any files open in VS Code, you’ll need to reload the editor to apply the changes.

      You can install other extensions by following the same process described for the PHP Intelephense extension, but be aware that some extensions will require additional software to be installed on your system. Check the extension documentation to make sure you have requirements set appropriately.

      Step 2 — Importing or Creating a New PHP Project

      To import an existing PHP project into VS Code, click on the first icon on the left menu bar or type CTRL + SHIFT + E to access the file explorer. Click the Open Folder button and select your project’s directory. In case you are creating a new project, you can create a new folder and select that as your project directory.

      The gif shows how to import a PHP project to VS Code

      The explorer window will now show the project’s directory tree, giving you quick access to files and directories on your project.

      Step 3 — Customizing Theme and Editor Font (Optional)

      Although not necessary, it is often a good idea to customize the appearance of your editor to make it more comfortable to use in the longer term. As a developer you may spend several hours every day looking at an IDE such as VS Code, and for that reason it’s important to make sure the editor font has an appropriate size, and the contrast is enough for good readability without tiring your eyes too quickly.

      You may want to experiment with different themes and fonts in order to find a custom setup that works well for you.

      Changing VS Code Theme

      VS Code comes with a few different themes that allow you to change the colors used in the editor interface and in the code highlighting. Both dark and light styles are included by default.

      Go to File -> Preferences -> Color Theme or type CTRL + K + T to select a different theme for VS Code.

      The gif shows how to change VS Code theme

      You can also install theme extensions to further customize VS Code’s appearance. If you search for theme within the extensions tab (CTRL + SHIFT + X), you’ll find several theme extensions in different styles and colors, including color schemes ported from other popular editors and platforms.

      Adjusting the Font

      Although the default VS Code font settings will be good enough for many users, you may want to adjust the size and the type of the editor font for increased readability.

      If you would like to modify the font size or change to another type, you can go to File -> Preferences -> Settings, then choose Text Editor on the left menu. Then, click on Font in the submenu that opens up. That section contains font family and size settings which you can tweak as preferred.

      The gif shows how to change VS Code editor font size

      The changes are immediately saved and applied to all current open files.

      Conclusion

      Visual Studio Code is a lightweight yet powerful code editor that can be customized to suit the needs of most developers. In this guide, you learned how to install and configure the PHP Intelephense extension for extra support while working on PHP projects, how to import and create new projects within VS Code, and how to customize the editor appearance for a more comfortable coding experience.

      For more tutorials on Visual Studio Code, check our VS Code tag page. If you’d like to learn more about PHP development, you can refer to our How To Code in PHP series for an introduction to the language, and our PHP tag page for more PHP tutorials.



      Source link

      Cara Memformat Kode dengan Prettier di Visual Studio Code


      Pengantar

      Memformat kode secara konsisten merupakan tantangan, tetapi alat pengembang modern memungkinkan pengembang mempertahankan konsistensi secara otomatis di seluruh basis kode tim Anda.

      Dalam artikel ini, Anda akan menyiapkan Prettier untuk memformat kode Anda secara otomatis di Visual Studio Code, yang juga dikenal sebagai VS Code.

      Untuk keperluan demonstrasi, inilah kode sampel yang akan Anda format:

      const name = "James";
      
      const person ={first: name
      }
      
      console.log(person);
      
      const sayHelloLinting = (fName) => {
      console.log(`Hello linting, ${fName}`)
      }
      
      sayHelloLinting('James');
      

      Jika sudah biasa memformat kode, Anda mungkin memperhatikan beberapa kesalahan langkah:

      • Campuran tanda kutip tunggal dan ganda.
      • Properti pertama objek person harus berada di barisnya sendiri.
      • Pernyataan konsol di dalam fungsi harus diinden.
      • Anda mungkin atau mungkin tidak suka tanda kurung opsional yang mengurung parameter fungsi panah.

      Prasyarat

      Untuk mengikuti tutorial ini, Anda perlu mengunduh dan menginstal Visual Studio Code.

      Untuk bekerja dengan Prettier di Visual Studio Code, Anda perlu menginstal ekstensi. Caranya, cari Prettier - Code Formatter di panel ekstensi VS Code. Jika Anda menginstalnya untuk pertama kali, Anda akan melihat tombol install sebagai ganti tombol uninstall yang ditunjukkan di sini:

      Readme ekstensi Prettier

      Langkah 1 — Menggunakan Perintah Format Document

      Dengan ekstensi Prettier yang telah terinstal, kini Anda dapat memanfaatkannya untuk memformat kode. Untuk memulai, mari kita mendalami penggunaan perintah Format Document. Perintah ini akan membuat kode Anda lebih konsisten dengan pengaturan jarak yang telah diformat, pelipatan baris, dan tanda kutip.

      Untuk membuka palet perintah, Anda dapat menggunakan COMMAND+ SHIFT + P di macOS atau CTRL + SHIFT + P di Windows.

      Dalam palet perintah, cari format, kemudian pilih Format Document.

      Perintah palet dibuka dengan hasil format

      Nanti, Anda mungkin diminta memilih format yang akan digunakan. Caranya, klik tombol Configure:

      Konfirmasi untuk memilih format asali

      Kemudian, pilih Prettier – Code Formatter.

      Memilih Prettier

      Catatan: Jika Anda tidak melihat konfirmasi untuk memilih format asali, Anda dapat mengubahnya secara manual di Settings. Atur Editor: Default Formatter ke ebsenp.prettier-vscode.

      Kode Anda sekarang telah diformat dengan jarak, pelipatan baris, dan tanda kutip yang konsisten:

      const name="James";
      
      const person = { first: name };
      
      console.log(person);
      
      const sayHelloLinting = (fname) => {
        console.log(`Hello linting, ${fName}`);
      }
      
      sayHelloLinting('James');
      

      Ini juga dapat digunakan di berkas CSS. Anda dapat mengubah kode dengan indentasi, kurung kurawal, baris baru, dan titik-koma yang tidak konsisten menjadi kode yang diformat dengan baik. Misalnya:

      body {color: red;
      }
      h1 {
        color: purple;
      font-size: 24px
      }
      

      Akan diformat menjadi:

      body {
        color: red;
      }
      h1 {
        color: purple;
        font-size: 24px;
      }
      

      Karena kita telah mendalami perintah ini, mari kita lihat cara mengimplementasikannya agar dijalankan secara otomatis.

      Langkah 2 — Memformat Kode saat Disimpan

      Sejauh ini, Anda harus menjalankan perintah secara manual untuk memformat kode. Untuk mengotomatiskan proses ini, Anda dapat memilih pengaturan di VS Code agar berkas Anda diformat secara otomatis saat disimpan. Hal ini juga memastikan bahwa kode tidak akan diperiksa karena kontrol versi yang tidak diformat.

      Untuk mengubah pengaturan ini, tekan COMMAND +, di macOS atau CTRL +, di Windows untuk membuka menu Settings. Setelah menu dibuka, cari Editor: Format On Save dan pastikan opsi itu telah dicentang:

      Editor: Format On Save dicentang

      Setelah ini diatur, Anda dapat menulis kode seperti biasa dan secara otomatis akan diformat saat menyimpan berkas.

      Langkah 3 — Mengubah Pengaturan Konfigurasi Prettier

      Prettier melakukan banyak hal untuk Anda secara asali, tetapi Anda juga dapat menyesuaikan pengaturannya.

      Buka menu Settings. Kemudian, cari Prettier. Ini akan menampilkan semua pengaturan yang dapat Anda ubah:

      Pengaturan Konfigurasi untuk Prettier

      Berikut ini beberapa pengaturan paling umum:

      • Single Quote – Memilih antara tanda kutip tunggal dan ganda.
      • Semi – Memilih jika akan menyertakan atau tidak menyertakan titik-koma di akhir baris.
      • Tab Width – Menentukan jumlah spasi yang Anda inginkan untuk menyisipkan tab.

      Kelemahan menggunakan menu pengaturan bawaan di VS Code adalah tidak menjamin konsistensi di semua pengembang dalam tim Anda.

      Langkah 4 — Membuat Berkas Konfigurasi Prettier

      Jika Anda mengubah pengaturan di VS Code, orang lain mungkin memiliki konfigurasi yang sepenuhnya berbeda di mesin mereka. Anda dapat membuat pemformatan yang konsisten untuk tim dengan membuat berkas konfigurasi bagi proyek Anda.

      Buat berkas baru bernama .prettierrc.extension dengan salah satu ekstensi berikut:

      Berikut ini contoh berkas konfigurasi sederhana yang menggunakan JSON:

      {
        "trailingComma": "es5",
        "tabWidth": 4,
        "semi": false,
        "singleQuote": true
      }
      

      Untuk lebih spesifik mengenai berkas konfigurasi, lihat Dokumentasi Prettier. Setelah membuat dan memeriksanya di proyek, Anda dapat memastikan bahwa setiap anggota tim mengikuti aturan pemformatan yang sama.

      Kesimpulan

      Memiliki kode yang konsisten adalah praktik yang baik. Hal ini sangat bermanfaat saat bekerja di proyek bersama beberapa kolaborator. Menyepakati seperangkat konfigurasi akan membantu dalam kemudahan membaca dan memahami kode. Akan ada lebih banyak waktu yang dapat dicurahkan untuk memecahkan masalah teknis yang menantang, bukannya berkutat dengan masalah yang telah diselesaikan seperti indentasi kode.

      Prettier menjaga konsistensi dalam pemformatan kode Anda dan mengotomatiskan prosesnya.



      Source link