Configuring Visual Studio Code

Last updated on
22 March 2024

Overview

Visual Studio Code (VS Code) is a free tool for editing and debugging Web apps based on the Visual Studio Code - Open Source code base maintained by Microsoft. VS Code is available for Mac, Linux and Windows. Note that an alternate build of VS Code exists, called VSCodium.

VS code provides a bunch of functionalities out of the box, like integration with Git and debugging. Besides that it can be extended using extensions. They can be installed using the extensions pane, accessing View -> Extensions. Below is a list of useful extensions to use during Drupal development.

The following is a list of recommended official and contributed extensions that will allow you to configure Visual Studio Code for Drupal PHP and JavaScript development.

  • PHP Sniffer & Beautifier: Combines both phpcs and phpcbf for checking Drupal coding standards in one handy extension.
  • Eslint: Linting support for JavaScript files. See here for more information.
  • PHP DocBlocker: Provides auto-complete for PHP docblocks.
  • PHP Debug: Provides launch configuration support for XDebug. Requires XDebug.

Intellisense Extensions for PHP

The intellisense extension you may want to use may vary based on your license requirements and Drupal web site. See below.

  • PHP Intelephense (bmewburn.vscode-intelephense-client): provides support for PHP code completion and intellisense that supports any PHP file extension (module, inc, etc...).
    • This extension is dual-licensed with the following licenses:
      • Under the MIT license, as a free extension with basic functionality as "nagware".
      • Under the proprietary, non-free Intelephense License, offering premium functionality at a cost.

This list is specific to modern Drupal, i.e., 8 and later, and includes Composer and Twig integrations.

  • Drupal: Provides syntax highlighting, hook completion, twig completion, service completion, global variables completion, code checking Drupal coding standards (phpcs, coder), document formatting by standards (phpcbf), searching in Drupal API Documentation, translation autocomplete (php, twig, js), and validation and autocomplete for YAML files (note, that the Syntax highlighting will conflict with PHP Sniffer & Beautifier if both are setup).
  • Drupal Smart Snippets: Adds rich language support for the Drupal 9 / 10 Hooks API. 
  • Composer extension: Provides an interface to Composer. It also provides schema validation for composer.json configuration files.
  • Twig Language 2: Provides snippets, syntax highlighting, hover, and formatting for the Twig file format.
  • YAML: Provides comprehensive support for YAML Language.

Configuring the Editor

Visual Studio Code displays its configuration on a per-project (Workspace) and global (User) level. Each configuration file is formatted as a JSON object (See documentation: User and Workspace Settings).

Default configurations can be overridden by accessing Preferences -> User Settings. By default, VS Code defaults are fine for Drupal, just a few tweaks are required.

The following breaks down and explains settings related by category or extension.

Editor Settings

The following settings are related to basic formatting for PHP, CSS, JavaScript or HTML files. These settings can be used as-is in either User or Workspace settings. If you use Visual Studio Code for other projects that use a different line length, tab/space size, then it would be better to add these settings to your Drupal site, module, theme or installer Workspace.

Change this by navigating to the User or Workspace settings page, and clicking the 'Open Settings (JSON)' button in the tab bar.

{
  "breadcrumbs.enabled": true,
  "css.validate": true,
  "diffEditor.ignoreTrimWhitespace": false,
  "editor.tabSize": 2,
  "editor.autoIndent": "full",
  "editor.insertSpaces": true,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": false,
  "editor.renderWhitespace": "boundary",
  "editor.wordWrapColumn": 80,
  "editor.wordWrap": "off",
  "editor.detectIndentation": true,
  "editor.rulers": [
    80
  ],
  "files.associations": {
    "*.inc": "php",
    "*.module": "php",
    "*.install": "php",
    "*.theme": "php",
    "*.profile": "php",
    "*.tpl.php": "php",
    "*.test": "php",
    "*.php": "php",
    "*.info": "ini"
  },
  "files.trimTrailingWhitespace": true,
  "files.restoreUndoStack": false,
  "files.insertFinalNewline": true,
  "html.format.enable": true,
  "html.format.wrapLineLength": 80,
  "telemetry.telemetryLevel": "off",

  /* PHP Intelephense (bmewburn.vscode-intelephense-client) */
  "intelephense.environment.includePaths": [
    "core/",
    "core/includes",
    "../vendor/"
  ],
}

PHP Drupal Coding Standards Configuration (using PHP Sniffer & Beautifier)

Note, that "PHP Sniffer & Beautifier" will conflict with the Syntax highlighting of the "Drupal" extension. Both the formatter and the linter following Drupal coding standards are already integrated in the "Drupal" extension. Use the "PHP Sniffer & Beautifier" Extension if you only want linting and formatting without the other "Drupal" extension features.

Code checking and formatting require the following packages:

composer require --dev drupal/core-dev

Linting

Visual Studio Code can restrict and lint your code to Drupal coding standards by using the PHP CodeSniffer configuration provided by drupal/coder. These are provided in Drupal Core as well as PHPStan as part of the drupal/core-dev composer package.

Add the following linter settings:

{
  "phpsab.snifferEnable": true,
  "phpsab.standard": "Drupal,DrupalPractice",
  "phpsab.snifferArguments": ["--extensions=inc,theme,install,module,profile,php,phtml"],
}

Formatting

Add the following formatter settings:

{
  "phpsab.fixerEnable": true,
  "phpsab.fixerArguments": ["--extensions=inc,theme,install,module,profile,php,phtml"],
  "[php]": {
    "editor.defaultFormatter": "valeryanm.vscode-phpsab"
  },
}

Now, pressing "CTRL + ALT + F" will format the current document using the PHP CodeSniffer configuration provided by drupal/coder (if installed correctly, read the CodeSniffer documentation for more information).

PHP validation

The following settings are related to checking that PHP code is valid. Copy and paste the following snippet into your configuration JSON, and change the executablePath setting to a valid path to the "php" or "php.exe" executable.

{
  "php.validate.enable": true,
  "php.validate.executablePath": "/path/to/php",
  "php.validate.run": "onType"
}

PHP Intelephense / IntelliSense 

Using the PHP Intelephense extension requires turning off the default PHP suggestions provided by Visual Studio Code. Disable the built-in VSCode PHP Language Features.

  1. Go to Extensions.
  2. Search for @builtin php
  3. Disable PHP Language Features. Leave PHP Language Basics enabled for syntax highlighting.

PHP Docblocks

The PHP Docblocker extension auto-completes comment documentation blocks. Add the following configuration to your configuration JSON to enable and configure the extension to use short names such as "bool" or "int" rather than the long name "boolean" or "integer".

{
  "php-docblocker.gap": true,
  "php-docblocker.useShortNames": true
}

JavaScript Coding Standards and IntelliSense Configuration

Drupal uses ESlint integrating the Airbnb config and the Prettier config to make sure the JavaScript code is consistent and free from syntax errors and leaking variables.

To properly set up ESLint, simply move the core's package.json "web/core/package.json" into your project's root directory, and install all of its dev dependencies using npm install (This will also let the VSCode integrated JS IntelliSense pick up on all the libraries used, which results in method suggestions and more, when developing Drupal contrib modules / themes).

Alernatively, you can also require the ESLint packages only running the following in your root directory (This won't setup the dev libraries for JS IntelliSense):

npm init -y
npm install --save-dev eslint@latest eslint-plugin-import@latest eslint-plugin-yml@latest eslint-config-airbnb-base@latest prettier@latest eslint-config-prettier@latest eslint-plugin-prettier@latest 

After following one of the approaches, you need to set the following VSCode (workspace) settings afterwards:

  "javascript.validate.enable": true,
  "javascript.format.enable": true,
  "eslint.format.enable": true,
  "eslint.enable": true,
  "prettier.configPath": "web/core/.prettierrc.json",
  "eslint.workingDirectories": [
    "./web"
  ],
  "[javascript]": {
    "editor.defaultFormatter":"dbaeumer.vscode-eslint",
  },

Done! EsLint is setup as your js linter and formatter.

To properly configure the JS Intellisense in VSCode, you simply install all the packages in the core's package.json (as shown above) and add a "jsconfig.json" in your project's root directory, with the following contents:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES6"
  },
  "include": [
    "web/core/misc"
  ]
}

This way, IntelliSense will additionally pickup on all the js files included in core.

Composer

The Composer extension provides an interface to Composer dependency manager for PHP. It also provides schema validation for composer.json configuration files. All composer commands are available through the Command Pallet using F1. This can be added either to the Workspace Settings or globally to the User Settings.

{
  "composer.enabled": true,
  "composer.executablePath": "/usr/local/bin/composer"
   Mac & Linux -- or -- Windows
  "composer.executablePath": "C:\\ProgramData\\ComposerSetup\\bin\\composer.bat"
}

Twig Language

Twig Language 2 is a Visual Studio Code extension that provides snippets, syntax highlighting, hover, and formatting for the Twig file format. If you work in both Drupal 7 and Drupal 8 you may want to add these settings to your Workspace Settings for your Drupal 8 sites. Add these lines to your VSCode settings to get emmet and HTML Intellisense working and also to associate HTML files as twig syntax.

{
  "files.associations": {
    "*.html": "twig",
  },
  "emmet.includeLanguages": {
    "twig": "html"
  },
}

Configuring XDebug

Visual Studio Code uses "launch" configurations to provide support for debugging as well as other actions. Please read the drupal.org Xdebug debugging documentation page for instructions about configuring XDebug.

To create a launch configuration for XDebug,

  1. Click the Debug menu icon on the left-side (Command/Ctrl-Shift D).
  2. Click the Dropdown menu with "No Configurations" listed in it, and then choose "Add Configuration".
  3. Add the snippet below in the Editor pane titled "launch.json" and save.
    • The "serverSourceRoot" is optional and used for Remote Debugging.
  4. Click the Play button (green triangle) to start debugger, and go to your local Drupal web site with the XDEBUG_SESSION_START=idekey query parameter where idekey is the value you configured in XDebug.
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for XDebug",
      "type": "php",
      "request": "launch",
      "port": 9000,
      "pathMappings": {
        "/path/to/drupal/webroot": "${workspaceFolder}"
      },
      "xdebugSettings": {
        "show_hidden": 1
      }
    }
  ]
}

Example launch.json (ubuntu vscode xdebug V3):

In XDebug V3 port changes from 9000 to 9003. XDebug Chrome plugin eliminates the need for query parameter mentioned above.

{
  "version": "0.2.0",
  "configurations": [{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "port": 9003,
    "xdebugSettings": {
      "show_hidden": 1
    }
  }]
}

Configuring JavaScript Debugger

You can configure Visual Studio Code to stop at breakpoints in Drupal JavaScript files by using Microsoft's "Debugger for Chrome" extension. Similar configuration can be added for Mozilla Firefox (Debugger for Firefox) or Microsoft Edge (Debugger for Edge) respectively.

  1. Add a new launch configuration from the Debug > Add Configuration menu.
  2. Choose "Chrome: Launch" or "Chrome: Attach" options.
  3. Specify the URL of the Drupal site to debug e.g. "https://drupal.org".
  4. Specify the webRoot if different from the current directory e.g. "${workspaceFolder}".
  5. Choose the "Launch Chrome" option from the Debug side pane.
  6. Click the green play button (F5) to start the debugger.
  7. Go to the URL specified in #3 after adding a breakpoint (F9) on a line of code in the editor gutter such as inside the Drupal.t function.
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Launch Chrome",
      "url": "https://drupal.org",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

License

Visual Studio Code may have a different license depending on the means of distribution. The software package available from Microsoft is compiled with additional configuration and software that falls under the proprietary Microsoft Software License. The primary source code is licensed under the MIT License, and alternative and open source packages may exist for your operating system.

One alternative build is called VSCodium, and it is MIT licensed.

Help improve this page

Page status: No known problems

You can: