Blog posts under the VS Code tag https://webdevstudios.com/tags/vs-code/ WordPress Design and Development Agency Tue, 09 Jul 2024 21:07:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the VS Code tag https://webdevstudios.com/tags/vs-code/ 32 32 58379230 Debugging React with VS Code and Chrome https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/ https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/#comments Thu, 06 Jul 2023 16:00:03 +0000 https://webdevstudios.com/?p=26056 Have you ever considered using a debugger for your React project but decided to keep on using console.log() instead because you thought it would be a pain to set up proper debugging? I did, until one day, I needed to get into the weeds on a project, and I figured I’d try and set up Read More Debugging React with VS Code and Chrome

The post Debugging React with VS Code and Chrome appeared first on WebDevStudios.

]]>
Have you ever considered using a debugger for your React project but decided to keep on using console.log() instead because you thought it would be a pain to set up proper debugging?

I did, until one day, I needed to get into the weeds on a project, and I figured I’d try and set up debugging in hopes of making my life easier. I was delighted to find out how easy it was! In this post, I’ll demonstrate how to debug a React project using VS Code and Chrome.

To demonstrate how to set things up, I’m going to use Vite and React to set up a React project. You’ll need to have VS Code and NPM installed.

Set Up a Workspace in VS Code

First, create a directory for our workspace. Then Open the directory in VS Code. Save the workspace.

I used D:devtrainingdebugging-react.

Create a React Starter Project Using Vite

From VS Code, open up this location in the integrated terminal and run the following command to create a starter project: npm create vite@latest

Create a Vite project

Follow the prompt from Vite. Give the project a name (I used vite-demo ). Select React for the framework and JavaScript for the variant.

Once that’s all set, change directories into the project folder that you assigned, run npm install.

Install packages

Once the installation is complete, start Vite by running npm run dev.

Run Vite

We can see that our project is running on localhost, port 5173. A browser window will be opened with the project:

Vite + React demo page

Create and Configure a launch.json File in VS Code

Now we need to create a launch.json file. Click the Debug icon (1), then create a launch.json file (2). The launch.json file will be located in your workspace’s .vscode directory.

Create launch.json file

Select the location:

Select the location

Select Chrome for the debugging type:

Debugging type: Chrome

This will open the launch.json file in a tab. (1) Set the port to whatever was specified by Vite earlier (5173 by default), and (2) add the subdirectory your project is into the webRoot option if you have your project in a subdirectory like I do here (/vite-demo).

Configure launch.json file in VS Code

Add a Breakpoint to the Code

Now open up your project’s src/App.jsxfile (1) and (2) add a breakpoint to line 20. We’re going to debug the count variable.

Add a breakpoint

Start Debugging Your React Project!

OK, we’re getting close! Now click the Start button to start debugging. This will launch our app in a new Chrome window.

Start debugging

The app is paused for debugging.

App opened for debugging in Chrome

A debugging session is now active in VS Code. We can use the debugging control bar to step through and inspect the code.

Debugging session is now active

We can interact with the app and see the value of the counter increase after clicking the count button.

Click the counter

Observe counter value

Here’s a quick screen capture showing this in action:

Debugging screen capture

One thing to note is that, by default, React.StrictMode is enabled in dev mode, so your app will be run twice. See the docs for details on Strict Mode.

That’s all there is to setting up basic React debugging in VS Code and Chrome. I hope this helps you to more efficiently debug your React projects.


Are you struggling with WordPress security? Our free guide teaches you everything you need to know to protect your site. Download and read our “Guide to WordPress Security” to safeguard your website.

The post Debugging React with VS Code and Chrome appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2023/07/06/debugging-react-with-vs-code-and-chrome/feed/ 1 26056
Debugging WordPress Using Xdebug, Local, and VS Code https://webdevstudios.com/2022/10/06/debugging-wordpress/ https://webdevstudios.com/2022/10/06/debugging-wordpress/#comments Thu, 06 Oct 2022 16:00:51 +0000 https://webdevstudios.com/?p=25376 This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen. Getting things set up correctly can be tricky. That’s where this tutorial helps. Xdebug Xdebug is a powerful tool for debugging PHP applications. It conveniently comes Read More Debugging WordPress Using Xdebug, Local, and VS Code

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen.

Getting things set up correctly can be tricky. That’s where this tutorial helps.

Xdebug in action

Xdebug

Xdebug is a powerful tool for debugging PHP applications. It conveniently comes bundled with Local.

We’re using VS Code for our code editor in this tutorial, as well as some other tools I’ve listed below. Everything included here is the current release and version numbers are noted just in case it might be helpful since things change.

Prerequisites

  • Local v6.4.2+6012: A local WordPress development environment, formally known as Local by Flywheel
      • PHP v7.4.1/v7.3.5/v8.0: Selectable via the Local UI. Choose v7.4.1 or v 7.3.5 for now because PHP 8 has a different Xdebug setup we’ll cover at the end of the article.
  • VS Code v1.70.2: Code editor
  • PHP Debug by Xdebug for VS code v1.27.0: VS Code extension which allows VS Code to talk to Xdebug
  • Xdebug Helper browser extension: Used for explicitly enabling or disabling debugging sessions

I use Windows because that’s what makes me happy, but this guide applies to other environments as well. I just wanted to note that, since the paths I’ll be referencing are Windows-y.

Create a Site in Local

Once all of the prerequisites have been installed and activated, you’ll need to create a new WP site in Local if you don’t have one already. When PHP Versions 7.3.x or 7.4.x are selected in Local, Xdebug Version 2 is used.

When PHP Version 8 is selected, Xdebug Version 3 is used. We’re going to use PHP Version 7.4.1 to start off with and will cover PHP Version 8 at the end of the article.

I’ve named my site xdebugvscode.test. Here are its settings:

Local site settings

Set Up php.ini.hbs Directives

Now that the site has been created, let’s double-check the Xdebug configuration directives in the site’s php.ini.hbs file. This file is located under your site’s conf/php directory.

For me, the path is D:devlocal-sitesxdebugvscodeconfphpphp.ini.hbs. Scroll to the bottom of the file under the [xdebug] section, and verify that you have the directives below set accordingly. If you need to make any changes, be sure to restart your Local site.

; Enable remote debugging.
xdebug.remote_enable=1

; If enabled, the xdebug.remote_host setting is ignored and
; Xdebug will try to connect to the client that made the HTTP request.
; It checks the $_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['REMOTE_ADDR'] variables to find out remote IP
xdebug.remote_connect_back=Off

; Set the port that Xdebug connects to.
xdebug.remote_port="9000"

; Disable the profiler.
xdebug.profiler_enable=0

; Set the profiler's output directory for when we're profiling.
xdebug.profiler_output_dir = "D:/dev/xdebug-profiler-output"

A Note About the php.ini.hbs File When Switching PHP Versions

If you ever change the PHP version for your Local site, Local will save the settings for the previous install of PHP under the {local-site-dir}/conf/php/php-{version-number}directory.

For example, I started out with PHP Version 7.4.1 installed, then switched to PHP Version 7.3.5. Local made a copy of my PHP Version 7.4.1 settings under D:devlocal-sitesxdebugvscodeconfphp-7.4.1.

If you change PHP versions and made any modifications to Local’s php.ini.hbs file, you’ll need to make the changes again, if this is the first time the PHP version has been activated. After that, if you swap between PHP versions, your setting changes will be preserved.

Ensure Xdebug Is Running

To make sure that Xdebug is running, create a file named pi.php in the root of your site and add the following code to it:

<?php
// Output information about PHP's configuration.
phpinfo();

location of the ph.php file

Now load up https://yoursite.test/pi.php and make sure that Xdebug is running. Find the Xdebug section; it will look something like this:
php_info() output
If you’re not seeing this, then Xdebug is not running. Double-check the php.ini.hbs file to ensure that Xdebug is enabled.

Activate Xdebug Helper Browser Extension

Once you’ve installed and activated the Xdebug Helper extension for your preferred browser, make sure to enable debugging by clicking on the icon and selecting Debug. The little bug icon will turn green letting you know that the browser extension will set the appropriate flag to turn on debugging.

Enable the Xdebug helper extension

Open Local Site in VS Code and Save a Workspace

Once the site has been created, go to File > Open Folder in VS Code, then navigate to the site’s directory. Now, save the workspace by going to File > Save Workspace As… and then give the workspace a name.

Install and Activate PHP Debug Extension for VS Code

The PHP Debug extension for VS Code helps to bring everything together. Locate the extension in VS Code’s Extension Browser, and activate it. Make sure to select the one published by the Xdebug team, since there are a few extensions with the same name.

PHP debug extension for VS Code

 

Create a launch.json File for Your Workspace

Next, we will create a launch.json file for our workspace. Click on VS Code’s debugging icon to open the debugging panel, then click on the create a launch.json file link.

Create launch.json step 1

Now select the name of your workspace which you created earlier.

Create launch.json step 2

VS Code will populate the launch.json file with defaults, but we’re going to replace them.

Create launch.json step 3

Go ahead and delete the entire contents of the default launch.json, replace the contents with the settings below, then save the file.

The launch.jsonwill be stored at {local-site-name}/.vscode/launch.json. So, mine is saved at D:devlocal-sitesxdebugvscode.vscodelaunch.json.

 

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for Xdebug",
      "type": "php",
      "request": "launch",
      "port": 9000,
      "log": false,
      "maxConnections": 1, // @see  https://github.com/xdebug/vscode-php-debug/issues/604
      "xdebugSettings": {
        "resolved_breakpoints": "0", // @see https://github.com/xdebug/vscode-php-debug/issues/629 and https://stackoverflow.com/a/69925257/3059883
        "max_data": 512,
        "show_hidden": 1,
        "max_children": 128
      }
    }
  ]
}

When using Local’s PHP Version 7.3.x or 7.4.x, the version of Xdebug in use will be 2.9.0, which had a bug that caused some weirdness with breakpoints. I’ve added some links to the config file above which go into some more detail if you’re interested.

Check out the PHP Debug extension’s Github page for more information about supported settings.

Add a Breakpoint to Your Code

For the purposes of this debugging WordPress demo, I’m going to add a breakpoint to line 48 of  Twenty Twenty-Two’s functions.php file.

To add a breakpoint, hover over the gutter (just to the left of a line number) and a little orange dot will appear. Click it to add a breakpoint.

Click it again to remove it. You can add multiple breakpoints, and the debugger will stop on each one. To keep things simple here, I’ll just add the one.

Adding a breakpoint

Once your breakpoint has been added, you will see it listed in the lower left-hand corner of  VS Code’s debugger panel. It’s also possible to set breakpoints on Notices, Warnings, Errors, etc., but we’ll uncheck all of those for this example.

Debugger breakpoints

Start Debugging WordPress

We’re finally ready to start debugging WordPress! Open VS Code’s debugger panel and click the green triangle to start listening for Xdebug. Use the F5 shortcut.
Start debugging
Once VS Code is listening for Xdebug, the Debugger Controls window will be displayed. The bottom of the VS Code window will turn orange.

Listening for debugger

Now Xdebug is waiting to start the session. To kick things off, just load a page that will hit the breakpoint.

I’m just going to load the homepage of the test site I created. Once I hit refresh on the homepage of the test site, VS Code will be highlighted in the taskbar and the debugger will stop executing code on the breakpoint that I had previously set.

Once a debugging session has started, additional controls will be active on the Debugger Control Panel, and variables will be listed under the VARIABLES section of the Debugging Panel.

Inside a debugging session

We can now use the Debugger Controls to navigate through the codebase:

Debugger Controls

  • Pause/Run (F6): Resumes code execution. Debugger will stop on the next breakpoint if set.
  • Step Over (F10): Steps over a block of code.
  • Step Into (F11): Steps into a block of code.
  • Step Out (Shift + F11): Steps out of a block of code that was previously stepped into.
  • Restart (Ctrl + Shift + F5): Restarts the debugging session.
  • Stop (Shift+F5): Halts execution of the script.

The GIF at the top of this article demonstrates some basic usage of these controls.

Exploring Variables

We can also explore the values of local and global variables using the VS Code’s VARIABLES section within the Debugging Panel.

Exploring variables

PHP Version 8 + Xdebug Version 3 Set Up

When a Local site is configured to use PHP Version 8.X, the bundled version of Xdebug will be Version 3, and there are many changes from Versions 2 to 3.

These changes are covered thoroughly in this guide. Notably, Xdebug Version 3 defaults to port 9003 instead of 9000. I’m going to switch my Xdebug Version 3 setup to use port 9000 for consistency, so I don’t have to change anything in my launch.json file.

Here are the Xdebug directives in my PHP Version 8 site’s php.ini.hbs file. Note that I’ve commented out the line xdebug.start_with_request.

xdebug.mode=debug
xdebug.client_port="9000"
; xdebug.start_with_request=yes
xdebug.discover_client_host=yes

Now that we’ve switched our site to PHP Version 8 if we check the output of our pi.php file that we created earlier, we can see that Xdebug Version 3 is now loaded, where Version 2.9.0 was being used under our PHP Versions 7.3 and 7.4 sites.

Xdebug version 3

One of the cool features that comes bundled with Xdebug Version 3 is the addition of the xdebug_info() function. This is similar to the php_info() function, but it provides more detailed diagnostics for about the Xdebug setup.

To use it, simply add a file to your site’s web root. For example, xdebug-info.php , then add the following contents:

<?php
xdebug_info();

Load that file up in your browser, and you’ll see something like this:

xdebug_info output - debugger not listening

In the screenshot above, the diagnostics log is indicating a problem connecting to the host on port 9000. The reason for this is that I have not enabled VS Code to listen for debugging.

So, I tap F5 to enable debugging, and now when I reload my xdebug-info.php, the Diagnostics Log is clean, and I’m ready to debug. Thanks to fellow WebDevStudios Backend Engineer, Biplav Subedi, for this tip!

xdebug_info output - debugger is listening

Troubleshooting

One common issue that comes up when you’re debugging WordPress is that the debugger does not stop on the breakpoint that you’ve set. This is typically caused by a port conflict—some other process is already using the port that you’ve configured for debugging.

Make sure that no other application is using the port that was configured in the php.ini.hbs and launch.json file. If an application is already using the port you’ve specified, make sure to change your port to something that’s not in use.

To check for a port conflict, end your debugging session in VS Code then run the following command:

Windows CMD: netstat -an | find "9000"

Linux/Mac: sudo netstat -nap | grep ":9000"

You should not see any output after entering these commands. If you do, that means that a process is already using the port you’ve configured for Xdebug (9000) in our example. So you should either configure a different port in your php.ini.hbs and launch.json files, or locate the process that is tying up the port, and stop it/configure it to use a different port.

Bonus: Quick and Dirty Debugging

Sometimes, instead of using Xdebug, I prefer to simply log variables to WP’s error.log file using PHP’s error_log().

I find this handy for real quick stuff, though it’s really not the best way to debug WordPress when things get serious. For this setup, first, add the following statements to your site’s wp-config.php file:

define( 'WP_DEBUG', true ); // Debugging mode activated.
define( 'WP_DEBUG_LOG', true ); // Logs to wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // Don't add errors to the output.
define( 'SCRIPT_DEBUG', true ); // Load un-minified scripts.

Now, errors will be logged to your site’s wp-content/debug.log file. I typically keep this file open in a side panel of VS Code.

error logging to debug.log

I usually use this one-liner to output values to the debug.log file:  error_log( '$variable_name ' . var_export( $variable_name, true ) );

To make things easier, I trigger this one-liner using a VS Code User Snippet with the trigger logv. Here’s a copy of the debugging-related snippets I use. These are configured in VS Code under File > Preferences >  Configure User Snippets > PHP.

{
// Place your snippets for php here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// "Print to console": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"Log var_export()": {
"prefix": "logv",
"body": ["error_log( '$1 ' . var_export( $2, true ) );"],
"description": "Do a var_export( $variable ) to PHP error log."
},
"Log print_r()": {
"prefix": "logp",
"body": ["error_log( print_r( $0, true ) );"],
"description": "Do a print_r( $variable ) to PHP error log."
},
"Exit with var_dump()": {
"prefix": "xvd",
"body": ["exit( var_dump( $0 ) );"],
"description": "Exit with var_dump()"
},
"Exit with print_r()": {
"prefix": "xpr",
"body": ["exit( print_r( $0 ) );"],
"description": "Exit with print_r()"
},
"Detailed Error Log": {
"prefix": "logd",
"body": [
"error_log( print_r( (object)",
"t[",
"tt'line' => __LINE__,",
"tt'file' => __FILE__,",
"tt'dump' => [",
"ttt$0,",
"tt],",
"t], true ) );"
],
"description": "Detailed error logging"
},
"Log gettype()": {
"prefix": "logt",
"body": ["error_log( gettype( $0 ) );"],
"description": "Do a gettype( $variable ) to PHP error log."
},
"Debug Filters": {
"prefix": "logf",
"body": ["add_action( 'all', function() { error_log( var_export( current_filter(), true ) ); } );"],
"description": "Logs current filter."
}
}

Conclusion

That’s about it for this post on debugging WordPress using Xdebug, Local, and VS Code. Using Xdebug, you’ll be able to more efficiently and effectively debug code. If you’ve never used it before, I’m sure you will find that Xdebug is a helpful tool in your development arsenal.

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/10/06/debugging-wordpress/feed/ 6 25376
Quick Tip: Next.js Hello World App – Part 2 https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/ https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/#respond Tue, 15 Jun 2021 16:00:43 +0000 https://webdevstudios.com/?p=23827 In Part 1 of this series, I introduced you to the terminal, Node.js, and we spun up the Hello World Example from Next.js. In Part 2, we’re going use a code editor to create a React component, maybe even style it, then finally view it in a web browser. Note: There are dozens and dozens Read More Quick Tip: Next.js Hello World App – Part 2

The post Quick Tip: Next.js Hello World App – Part 2 appeared first on WebDevStudios.

]]>
In Part 1 of this series, I introduced you to the terminal, Node.js, and we spun up the Hello World Example from Next.js. In Part 2, we’re going use a code editor to create a React component, maybe even style it, then finally view it in a web browser.

Note: There are dozens and dozens of code editors out there. Don’t be afraid to experiment until you find the one that you like best. For this article, we’ll be using the wildly popular and open-source code editor VS Code from Microsoft.

Install VS Code

Visit Code.VisualStudio.com/Download.

This is a screenshot of the VS Code download page.

Click the blue button that matches your Operating System. For this article, I’ll be clicking Windows 7, 8, 10.

Once the file finishes downloading, double-click to run the installer. When prompted, select all the boxes:

Continue to click Next until VS Code has successfully been installed.

Open VS Code and the Hello World Folder

Now that VS Code is installed on your computer, double-click the icon on your desktop to open:

vscode welcome screen

Next, we’re going to find the hello-world folder we created in Part 1 of this series. It should be located in your User directory:

open hello world folder

Using your mouse, click on the hello-world folder, and then click the Select Folder button:

select hello world folder

You can safely close the Welcome dialog in VS Code. The following folders and files should be in the sidebar:

hello world folder structure

If you’ve made it this far, great! If not, be sure to catch up on Part 1 of this series.

Open the Integrated Terminal

One of my favorite features of VS Code is the integrated terminal. This feature allows you to use the terminal without app switching.

In the menu bar, click Terminal and then New Terminal:

open integrated terminal in vs code

You should now see the Terminal at the bottom of your screen:

vs code integrated terminal window

Type the following (or copy and paste) into your Terminal, and press Enter:

npm run dev

After a few seconds, you should see the following text appear:

the terminal after running npm run dev

Finally, open up your favorite web browser. In the address bar, type:

http://localhost:3000

the initial homepage view

Nicely done. You’re now set up! Behind the scenes, Webpack is watching for file changes and will automatically recompile the homepage when they’re detected.

Your First Component

Now that your development environment is up and running, let’s jump in and create your first component.

Create the Component Folder and File

In VS Code, click the New Folder icon in the sidebar:

vs code new folder icon

Name the folder components.

Click the components folder with your mouse, and then click the New File icon:

vs code new file icon

Name the file Button.js.

the new Button file

Create the Button Component

I’m not going to dive into how React or import work. For now, focus on creating a simple component. Feel free to type this out, or copy and paste, into Button.js

export default function Button() {
    return(
        <>
            <button>Click Me</button>
        </>
    )
}

VS Code should look exactly like:

the initial button component

Now save this file by clicking File and then Save.

Import Button Component

Now that you have a component (yay!), you’ll need to import it into the homepage.

In the sidebar, navigate to /pages/index.js and double-click your mouse on index.js to open.

VS Code should look similar to this:

the homepage file

At the top of the index.js file, type (or copy and paste) the following:

import Button from '../components/Button'

import the button component

After the </Link> component on line 10, click insert your mouse cursor, then create a new line by pressing Enter on your keyboard.

Now type:

<Button />

insert button component

Save this file by clicking File and then Save.

View the Button Component

Go back to your web browser. and you should already see:

view the button in a web browser

You now know how to create and import a React component. Great work!

Extra Credit: Style Button Component

That button don’t exactly pop; so let’s take one more step together and style the button using a common approach in React: CSS Modules. Next.js has native support for CSS Modules, so there’s nothing else to set up.

Create CSS Module

In the sidebar of VS Code, click on the components folder again, and click the New File icon.

Name the file Button.module.css.

css module for button file

Type (or copy and paste) the following into Button.modules.css:

.button {
  background: blue;
  color: white;
  margin: 0 16px;
  padding: 8px 16px;
}

basic button styles

Save the file by clicking File and then Save.

Import CSS Module

You’ve already imported a file before, so let’s reinforce that knowledge and do it again.

Double click the Button.js tab in VS Code to switch to it. At the top of the file, type (or copy and paste) the following:

import styles from './Button.module.css'

import that css module file

Nice. The last thing to do is use the styles in the button. Type (or copy and paste) the following inside the first <Button> tag:

className={styles.button}

use the styles in a class

The Button.js file should look exactly like this:

the finished button component

Save the file by clicking File and then Save.

Switch to your web browser, and both Webpack and Next.js should have already compiled your CSS. So, it’s ready to view:

Wrap Up

Congratulations! You’ve taken some very important first steps toward building modern apps with React and Next.js. Now that you’ve got the basics, you should take the official Learn Next.js course. Watch Lee Robinson’s YouTube playlist titled, “Learn Next.js,” and view our other articles about Next.js.

Finally, if you’re looking for an experienced web development agency to handle your next Headless WordPress project, get in touch with us today.

The post Quick Tip: Next.js Hello World App – Part 2 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/feed/ 0 23827
Speed Up Your Development with Visual Studio Code https://webdevstudios.com/2020/03/05/visual-studio-code/ https://webdevstudios.com/2020/03/05/visual-studio-code/#comments Thu, 05 Mar 2020 17:00:05 +0000 https://webdevstudios.com/?p=21768 Visual Studio (VS) Code was released on April 29, 2015 by Microsoft. In a very short time, it has taken the coding world by storm. As of 2020, nearly 51% of developers claim to use it as their primary development environment. This, in itself, is shocking. When it first came out, nobody expected a tool Read More Speed Up Your Development with Visual Studio Code

The post Speed Up Your Development with Visual Studio Code appeared first on WebDevStudios.

]]>
Visual Studio (VS) Code was released on April 29, 2015 by Microsoft. In a very short time, it has taken the coding world by storm. As of 2020, nearly 51% of developers claim to use it as their primary development environment.

This, in itself, is shocking. When it first came out, nobody expected a tool made by Microsoft to become so dominant. After all, Sublime Text and Atom (made by GitHub) were incredibly popular and had a large user base; Microsoft had a large hill to climb.

Microsoft did lots right when developing VS Code, but there are a few (okay, five) specific things that sick out (to me) that make it universally appealing. First and perhaps foremost, they integrate extensions as a primary function of the IDE.

This focus is obvious. It has a button in the activity bar! Extensions are popular in Atom and Brackets, as well (both very similar IDEs built on Electron), but neither have made extensions so accessible and simple. This means that if, for some reason, you want your editor to work differently, there’s probably an extension for that. If there isn’t one, you can code one yourself using their thorough documentation and API.

Secondly, Visual Studio Code is fast. Maybe not FAST like Sublime Text (which is built with C++, as opposed to JavaScript and HTML, implemented with Electron), but significantly faster than either Atom or Brackets. And you know what they say: you don’t have to be faster than a bear, you just have to be faster than the person next to you. The speed of VS Code makes similar editors feel sluggish and unresponsive.

Then there’s Git. Sublime doesn’t have it out of the box. Atom does, but VS Code just does it better. Want to git a lot of developers excited? Get Git right!

Microsoft made Visual Studio Code open-source, hosting it on GitHub. This was unexpected. Microsoft is not known for being open-source-friendly. Perhaps this was originally a foreshadowing of June 2018, when they bought GitHub for $7.5 billion. No matter what the reason, being open-source invigorated and built a community, quickly.

The last thing that sets them apart is actually two things that works as one: they have listened to their user base on GitHub, then have promptly fixed or added whatever had been requested. This responsiveness has captured many fans and caused Visual Studio Code to improve leaps and bounds in a short time. Today, they’re at nearly 60,000 commits with no signs of slowing down. Developers love them some pull requests (PRs) and lots and lots of commits.

(In comparison, Sublime Text 2 had, at one time, appeared to have stopped development entirely, with Sublime Text 3 seemingly forever in beta. It was eventually released on September 13, 2017.)

Speed Up / Customize / Tweak Your Development

Before you continue, I’ve got to break something to you. The following tips aren’t necessarily unique. I haven’t discovered hidden settings that nobody else has found.

Instead, the following pieces of advice aim to surprise you with a new keyboard shortcut or an extension you hadn’t heard about. I’d like to try to address almost all aspects of how you can modify or customize VS Code to your liking, not just list a bunch of neat extensions. If you need a more in-depth primer on everything Visual Studio Code, I recommend reading the official Getting Started Guide, which is fantastically thorough.

One last thing, all of the keyboard shortcuts are for MacOS; I chose to omit the Windows shortcut as opposed to getting some wrong. Here’s the Windows VS Code shortcuts reference, the MacOS shortcuts, and the Linux shortcuts.

Sound cool? Keep calm and develop on.

Visual Aids

Color Themes

If there’s one thing that you can do that will go furthest in enhancing your enjoyment and efficiency when using Visual Studio Code, it’s making sure you use a color theme that is legible and reduces your eye strain. A lot of developers will be staring at their IDE for hours at a time, so you owe it to yourself to find a theme that works for you.

Here are a few I’ve used for quite some time and enjoy a lot. You might notice these are all dark themes with nary a light one to be found. After trying a few light themes for a while, I just couldn’t get past the extra strain they put on my eyes. For me, when coding, darker is better. If lighter themes are your jam, check out some good ones here.

Cobalt 2 by Wes Bos

  • I recently started using Cobalt for Visual Studio Code and now also use it as my Firefox theme, although I prefer this one. I like that the focus is clearly on the editor with the side panels darkened the right amount. Additionally, highlighted elements are clear and pronounced. It’s really nicely done.
  • Search extensions for: wesbos.theme-cobalt2
  • VS Code Marketplace link
Cobalt 2

 

Monokai Pro (nagware – 10€ to remove the occasional popup, but it’s worth it!)

  • I used Monokai Pro for a couple years and found that the lower contrast really helped with long-term eyestrain. The developer has put a ton of work into this theme and it shows. It comes highly recommended, even though it’s a paid theme (although you can ignore the occasional nags, if you prefer).
  • Search extensions for: monokai.theme-monokai-pro-vscode
  • VS Code Marketplace link
Monokai Pro Filter Octagon

 

Material Theme (website or Github)

  • This is a theme I’ve actually not used for more than a brief time. However, with 1.7M installs, clearly people like it. Check it out if Material Design is your thing.
  • Search extensions for: equinusocio.vsc-material-theme
  • VS Code Marketplace link
Material Theme Palenight High Contrast

 

Monokai One Dark Vivid

  • This is a less popular theme, but I used it for a long time. I really loved the high-contrast rainbow color scheme but the ultra-high contrast might not be for everyone.
  • Search extensions for: ashpowell.monokai-one-dark-vivid
  • VS Code Marketplace link
Monokai One Dark Vivid

 

Bracket Colors

Extension: Bracket Pair Colorizer 2

  • Search extensions for: coenraads.bracket-pair-colorizer-2
  • VS Code Marketplace link
  • This also colors the indentation guides.

Icon Themes

I prefer the Material Icon Theme, but VS Code Great Icons are also… uh, great.

Material Icon Theme

VS Code Great Icons

Extensions

ACF Snippets

Auto Comment Blocks

    • You can easily insert multi-line comments. Just type /** + Enter and you’re good to go.
    • Search extensions for: kevinkyang.auto-comment-blocks
    • VS Code Marketplace link

Better Comments

  • This goes nicely with Auto Comment Blocks. Highlight TODOs and FIXMEs and NOTEs (and more) so they stand out in your code. It’s also very customizable.
  • Search extensions for: aaron-bond.better-comments
  • VS Code Marketplace link

Comment Anchors

  • I clearly love comments. This extension automatically adds an anchor, essentially a bookmark, to anything that says NOTE, TODO, FIXME, etc. It also creates a VS Code panel, so you can find all Anchors in a project or just the ones in the current file, which is handy.
  • Search extensions for: exodiusstudios.comment-anchors
  • VS Code Marketplace link

Settings Sync

  • This feature is absolutely fantastic if you use more than one computer and you want the exact same setup, even if you’re going from Mac -> Windows -> Linux. Everything is beautifully kept in sync.
  • Search extensions for: shan.code-settings-sync
  • VS Code Marketplace link

Search the WordPress Docs

  • If you can’t remember (like me) if get_permalink accepts the post object or just the ID, and whether or not it has any optional parameters, you’ll find this feature super useful. I have mine bound to cmd + F1 and set to open in a side-by-side panel.
  • Search extensions for: yogensia.searchwpdocs
  • VS Code Marketplace link

Path Intellisense

  • This is great if you need to include() a lot of files.
  • Search extensions for: christian-kohler.path-intellisense
  • VS Code Marketplace link

Highlight Matching Tag

  • So subtle, but it’s very useful. It gives you a bit of context, both as an underline as well as a gutter marker, and works with everything from functions to SCSS blocks to good ol’ HTML.
  • Search extensions for: vincaslt.highlight-matching-tag
  • VS Code Marketplace link

SCSS Formatter, SCSS Intellisense, SCSS Everywhere

  • If you write SASS, you need these.
  • Search extensions for: sibiraj-s.vscode-scss-formatter, mrmlnc.vscode-scss, gencer.html-slim-scss-css-class-completion
  • VS Code Marketplace – SCSS Formatter, SCSS Intellisense, SCSS Everywhere

Emmet

Emmet is a great time-saver, allowing you to write a bunch of custom HTML & CSS snippets on the fly. Pro tip: use multi-cursors (find out how below) to activate Emmet in a variety of spots at once.

Here’s a great tutorial on all the ins and outs of Emmet in VS Code. Some quick Emmet shortcuts can be found below.

  • HTML
    • div.header>ul.menu>li.menu-item*3
  • SCSS / CSS
    • Use TAB to trigger the following shortcuts. To enable TAB triggering, see the Settings below.
    • m > margin
    • p > padding
    • d > display: block
    • r > right
    • t > top
    • w > width
    • h > height

Useful Settings

Add the following to your Settings file (cmd + ,), or modify them with the Settings UI:

  • “files.trimTrailingWhitespace”: true
    • Always removes trailing space on lines.
  • “files.insertFinalNewline”:true
    • Add a newline at the end of the file.
  • “editor.smoothScrolling”: true
    • So smooooth.
  • “workbench.editor.enablePreviewFromQuickOpen”: false
    • If you’re using cmd + p to open files, don’t set them as previews.
    • This leaves files that you single-clicked in the file explorer as previews.
  • “extensions.ignoreRecommendations”: true
    • Hide the extension recommendations.
  • “editor.fontLigatures”: true
    • Turn on font ligatures. (See below.)
  • “emmet.triggerExpansionOnTab”: true
    • Let emmet trigger suggestions with the TAB key.
  • “telemetry.enableTelemetry”: false
  • “workbench.settings.enableNaturalLanguageSearch”:false
    • The above two settings disables data collection by Microsoft.
  • “editor.cursorBlinking”: “phase”
    • I prefer this to a blinking cursor.

Keyboard (& mouse) Shortcuts

If you want to be efficient, don’t take your hands off of the keyboard! As I mentioned at the top of the article, all of the keyboard shortcuts are for MacOS. You can find links to the keyboard shortcuts for all platforms here. Before starting in on the shortcuts, are you coming from a different IDE? If so, there’s probably a keymap for that!

Downloadable Keymaps:

Keyboard Shortcuts

The official Key Bindings list can be found here.

cmd + shift + p

  • Command Palette
  • Do anything by typing.

cmd + p

  • Open any file quickly with fuzzy search.

cmd + shift + .

  • Display and jump through your code tree via breadcrumbs.

cmd + shift + ;

  • Select current breadcrumb, then navigate with arrows.

cmd + ,

  • Open and play with your settings.

cmd + alt + click

  • Goto Definition in a side-by-side pane

cmd + l

  • Select whole line with cursor.
  • Works with multi-cursors

ctrl + j (note: NOT cmd)

  • Join line (Mac only)

shift + option + Up/Down

  • Duplicate line up or down

cmd + shift + k, cmd + c, cmd + v

  • Simply put your cursor on the line to manipulate. The whole line doesn’t have to be selected.
  • Delete line > cmd + shift + k
  • Copy / cut line > cmd + c / cmd + x
  • Paste line > cmd + v

cmd + d

  • Select word under cursor, highlight all occurrences of that word in the file.
  • Hit again to progressively select more of the same word.

cmd + shift + l

  • Select all occurrences of a word in current file.

shift + option + drag

  • Column mode
  • Alternatively, use the middle mouse button

cmd + shift + t

  • Reopen files that you recently closed in order (just like in your browser!).

cmd + shift + e, f, g, d, x

  • Focus panels > file explorer, find, git, debug, extensions (in order, from top to bottom)

Multi-cursors

  • Option + click
  • (Might be set to ctrl + click, toggleable in the Settings or in Selection > Switch to…)

shift + option + right (or Left)

  • Select everything inside brackets { }.
  • Use Right to expand selection to include next section.
  • Use Left to shrink selection.

Quickly toggle between terminal and editor focus

  • Add the following to your settings, modifying as desired:
    • { “key”: “ctrl+`”, “command”: “workbench.action.terminal.focus”, “when”: “editorTextFocus” }, { “key”: “ctrl+`”, “command”: “workbench.action.focusActiveEditorGroup”, “when”: “terminalFocus” },

Other cool things

Fonts with Ligatures

So, why use font ligatures at all, and what are they?

Ligatures are a font that will merge several characters into a single one, to make them more legible or to stand out in some way. In programming, that basically means you’ll see ⇒ instead of => and ≥ instead of >= and so on. Different fonts will support a different number of ligatures, so try a few to decide what works for you. Here’s an example of the ligatures supported in Fira Code:

Want to try some out? Cool. To start, enable ligatures in your settings by adding “editor.fontLigatures”:true, (or use the UI) then install and select one of the following fonts:

Good fonts for coding:

Zsh shell > Bash

    • Adding the settings manually: (cmd+.)
      • “terminal.integrated.shell.osx”:”/bin/zsh
      • “terminal.integrated.shell.linux”:”/bin/zsh”

Workspaces

  • You can have workspace-based settings!
    • Formatting
    • Color themes
    • Etc.
  • In one Workspace, you can open different folders which are not necessarily in the root folder.
    • File > Add Folder to Workspace

Get a Wider Monitor

No, really. Consider buying an ultrawide monitor. Check out the screen real estate! This is one of best things I’ve ever done to increase my productivity.

Cobalt 2

 

That’s all I’ve got. If I find some new efficiencies, I’ll add them here so be sure to check back periodically. Also, if you find some that I’ve missed, feel free to share them with me on twitter.

Have fun coding!

The post Speed Up Your Development with Visual Studio Code appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/03/05/visual-studio-code/feed/ 2 21768