← Back to DevBytes

WebStorm Code Snippets: Complete Guide

Introduction to WebStorm Code Snippets

WebStorm, JetBrains' powerful IDE for JavaScript and TypeScript development, offers a feature that can dramatically speed up your coding workflow: code snippets. Known internally as "Live Templates," these snippets allow you to insert predefined blocks of code with just a few keystrokes, complete with customizable placeholders and dynamic variables.

Whether you're writing boilerplate React components, setting up Express routes, or creating utility functions, mastering code snippets in WebStorm will save you hours of repetitive typing and reduce the chance of syntax errors.

What Are WebStorm Code Snippets?

Code snippets in WebStorm are reusable code fragments that you can insert into your editor using a short abbreviation followed by the Tab key. They are part of the broader Live Templates system, which supports:

Live Templates vs. Surround Templates

WebStorm distinguishes between two types of templates. Live Templates insert code at the cursor position, while Surround Templates wrap selected code. For example, wrapping a block of statements in a try-catch is a classic use case for surround templates.

Why Code Snippets Matter

Code snippets are more than just a convenience — they are a productivity multiplier. Here's why they matter:

Built-in Snippets in WebStorm

WebStorm ships with dozens of built-in live templates organized by category. Some commonly used ones include:

To see the full list, go to Settings/Preferences → Editor → Live Templates and expand the JavaScript, TypeScript, or React groups.

How to Use Existing Snippets

Using a snippet is straightforward. Type the abbreviation in the editor and press Tab (or Enter, depending on your configuration). WebStorm will expand the abbreviation into the full template and place your cursor at the first editable variable.

For example, typing fori and pressing Tab in a JavaScript file produces:

for (let i = 0; i < length; i++) {
    
}

The cursor jumps to length first, then to the body, allowing you to fill in values without touching the mouse.

Using Surround Templates

To use a surround template, select the code you want to wrap, then press Ctrl+Alt+T (Windows/Linux) or Cmd+Option+T (macOS). A menu appears with available surround templates like if, try/catch, for, and custom ones you've created.

Creating Custom Code Snippets

The real power of WebStorm snippets comes from creating your own. Here's a step-by-step guide.

Step 1: Open the Live Templates Settings

Navigate to Settings/Preferences → Editor → Live Templates. You'll see a tree of template groups. Click the + button to create a new template or a new group.

Step 2: Define the Template

Each template has four key fields:

Step 3: Use Variables in Templates

Variables in templates are wrapped in dollar signs, like $VAR$. Two special variables exist: $END$ marks where the cursor lands after all variables are filled, and $SELECTION$ represents the selected text in surround templates.

Here's an example template for a React functional component:

import React from 'react';

interface $ComponentName$Props {
  $END$
}

export const $ComponentName$ = (props: $ComponentName$Props) => {
  return (
    <div>
      $END$
    </div>
  );
};

When you type the abbreviation (e.g., rfc) and press Tab, WebStorm inserts the full component and lets you type the component name once — it automatically fills in both the interface name and the component reference.

Step 4: Configure Variable Defaults and Functions

Click Edit variables to assign default values or use built-in functions. Useful functions include:

For example, you can set the $ComponentName$ variable's default expression to capitalize(camelCase(fileNameWithoutExtension())), which automatically derives a component name from the file name.

Practical Snippet Examples

Example 1: Express Route Handler

Abbreviation: exroute

router.$METHOD$('$PATH$', async (req, res, next) => {
  try {
    $END$
    res.status(200).json({ success: true });
  } catch (error) {
    next(error);
  }
});

Variables: $METHOD$ (default: get), $PATH$ (default: /), $END$.

Example 2: TypeScript Interface

Abbreviation: tsint

interface $Name$ {
  $property$: $type$;
  $END$
}

This lets you quickly scaffold an interface and tab through the property name and type fields.

Example 3: React useState Hook

Abbreviation: ustate

const [$state$, set$State$] = useState($initial$);

Set the $State$ variable's expression to capitalize($state$) so that when you type the state name in lowercase, the setter name is automatically capitalized.

Example 4: JSDoc Comment Block

Abbreviation: jsdoc

/**
 * $description$
 * @param {$paramType$} $paramName$ - $paramDesc$
 * @returns {$returnType$} $returnDesc$
 */

Example 5: Console Error with Label

Abbreviation: cerror

console.error('$label$:', $value$);

Example 6: Jest Test Case

Abbreviation: jtest

describe('$describeName$', () => {
  it('should $expectation$', () => {
    $END$
  });
});

Example 7: Custom Error Class

Abbreviation: errclass

export class $Name$ extends Error {
  constructor(message: string) {
    super(message);
    this.name = '$Name$';
  }
}

Sharing Snippets with Your Team

WebStorm stores live templates in XML files under your configuration directory. To share them with your team, export the templates and commit them to your repository.

Exporting Snippets

In the Live Templates settings, select the templates or groups you want to share, click the export icon (a small save icon), and save the XML file to your project, for example at .idea/liveTemplates.xml or snippets/.

Importing Snippets

Team members can import the XML file by clicking the import icon in the same settings panel and selecting the file. Alternatively, place the XML file in the IDE's templates folder, and WebStorm will pick it up automatically.

Example XML Structure

<templateSet group="MyTeamSnippets">
  <template name="rfc" value="import React from 'react';

interface $ComponentName$Props {
  $END$
}

export const $ComponentName$ = (props: $ComponentName$Props) => {
  return (
    <div>$END$</div>
  );
};" description="React functional component" toReformat="true" toShortenFQNames="true">
    <variable name="ComponentName" expression="capitalize(camelCase(fileNameWithoutExtension()))" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="TypeScript JSX" value="true" />
    </context>
  </template>
</templateSet>

Best Practices for Code Snippets

1. Keep Abbreviations Short and Memorable

Use two to five character abbreviations that are easy to remember and type. rfc for React functional component, ustate for useState, and exroute for Express route are all clear and quick.

2. Use Meaningful Variable Names

Variable names like $ComponentName$ and $path$ are self-documenting. Avoid single-letter variables unless the context is obvious.

3. Leverage Variable Functions

Use functions like camelCase, capitalize, and fileNameWithoutExtension to reduce manual input. The less you type, the more productive you are.

4. Set the Right Context

Always define the applicable context for each template. A React snippet should not appear in a Node.js server file. Proper context prevents clutter in the completion popup and avoids accidental misuse.

5. Enable Reformatting

Check the Reformat according to style option so that inserted code automatically conforms to your project's formatting rules. This keeps your codebase clean without extra effort.

6. Avoid Over-Snippeting

Don't create snippets for code you write infrequently or for one-off scenarios. Snippets shine for repeated patterns. Too many snippets make the completion list noisy and hard to navigate.

7. Document Your Snippets

Always fill in the description field. When your team has dozens of shared snippets, clear descriptions help everyone find the right one quickly.

8. Version Control Your Snippets

Treat your snippet library like code. Store it in version control, review changes, and evolve it over time as your project patterns change.

9. Use $END$ Strategically

Place $END$ where you naturally want to continue writing after the snippet is filled. This keeps your hands on the keyboard and maintains flow.

10. Combine with Postfix Completion

WebStorm also supports postfix completion, which transforms an expression based on what you type after a dot. For example, typing myVar.log and pressing Tab becomes console.log(myVar). Combine live templates with postfix completion for maximum efficiency.

Advanced Techniques

Conditional Snippet Content

While WebStorm doesn't support conditional logic directly in templates, you can simulate it using variable defaults. For example, set a variable's default to a function that returns different values based on context.

Chained Variable Expressions

You can chain functions in variable expressions. For example, capitalize(camelCase(fileNameWithoutExtension())) first gets the file name, converts it to camelCase, then capitalizes the first letter — perfect for component names.

Snippets for File Templates

Beyond live templates, WebStorm supports File Templates that generate entire files. Configure these under Settings → Editor → File and Code Templates. For example, you can create a template that generates a complete React component file with imports, interface, and default export when you choose File → New → React Component.

Using $SELECTION$ for Surround Templates

To create a surround template, include $SELECTION$ in the template text. For example, a template that wraps code in a Promise:

new Promise((resolve, reject) => {
  $SELECTION$
});

After selecting code and pressing Ctrl+Alt+T, choose this template to wrap the selection inside the Promise constructor.

Troubleshooting Common Issues

Snippet Doesn't Appear

If your snippet doesn't show up in completion, check the applicable context. A snippet scoped to TypeScript won't appear in a plain JavaScript file. Also verify the abbreviation doesn't conflict with an existing one.

Variables Not Resolving

Make sure variable names in the template text match those in the Edit Variables dialog. A typo like $ComponetName$ instead of $ComponentName$ will cause the variable to be treated as plain text.

Tab Key Doesn't Expand Snippets

Check your keymap under Settings → Keymap and search for "Live Template." Ensure Tab is assigned as the expansion key and that no other plugin has overridden it.

Conclusion

WebStorm's code snippets, powered by the Live Templates system, are one of the most effective ways to boost your development speed and maintain consistency across your codebase. By starting with the built-in templates, gradually building a library of custom snippets tailored to your workflow, and sharing them with your team through version control, you can eliminate repetitive boilerplate and focus on what matters most — writing great software. Take some time to audit the code you write most frequently, convert those patterns into snippets, and you'll wonder how you ever worked without them.

— Ad —

Google AdSense will appear here after approval

← Back to all articles