Quantcast
Channel: Cool Feature – WebStorm Blog

Customizing the WebStorm layout

$
0
0

WebStorm layout has three types of major UI elements.

First of all, there’s the editor with the right and left gutters that show line numbers, status of VSC-modified lines, errors and warnings, and some other useful info.

Second, there are various tool windows such as the project view on the left with the project structure, the debugger tool window that displays when you start a debugging session, or the built-in terminal.

The third type of elements includes all the various bars like Navigation bar on the top or Status bar on the bottom. There’s also a Toolbar which is hidden by default, and a Tool buttons bar that shows icons corresponding to various tool windows.

Tip: You may notice numbers on the tool buttons; press Cmd+Number key / Alt-Number key to take you to the corresponding tool window.

You have a lot of flexibility in modifying the WebStorm layout. You can hide bars you don’t need via the View menu. You can also change the position of the tabs from the top to the left or right side of the editor, or hide them completely (see Preferences | Editor | General | Editor tabs).

ws-mininalistic-layout

All the tool windows can be dragged around, and they behave a bit different in various modes. In Docked mode, they stick to the side of the main IDE window, while in Floating mode they can be placed anywhere on the screen. To switch the mode, simply click the gear icon on the tool window.

One non-obvious thing here is that you can save your favorite layout as the default via the Window menu. Store the current layout as default, and then quickly go back to it if you’ve moved some things around by selecting Window | Restore default layout (or pressing Shift-F12).

With the Hide all tool windows action (Cmd-Shift-F12 / Ctrl+Shift+F12) you can maximize the editor and hide all the tool windows as the name suggest.

One next step you may want to try is the Distraction free mode. When you enable this mode, all the tool windows, side bars and even editor tabs are hidden, and you see only the code you’re working with. In other words, nothing distracts you anymore. To enable the Distraction free mode, select the View menu (or press Ctrl-` for the Quickly switch scheme popup) and then select Distraction free mode under View modes.

ws-distraction-free-mode

While working in the Distraction free mode, navigation between files is done with these shortcuts:

  • Cmd-E / Ctrl+E for Recent files
  • Cmd-Shift-O / Ctrl+Shift+N for Go to file
  • Cmd-Alt-O / Ctrl+Alt-Shift+N for Go to symbol

The Full screen mode expands WebStorm to the full screen and hides the top menu.

For live coding sessions on big screens, consider the Presentation mode. Only the editor is shown, and the font and all the UI elements are larger in size.

– JetBrains WebStorm Team


Angular 2 workflow in WebStorm

$
0
0

WebStorm is well-known for its AngularJS 1 support. WebStorm 2016.1 introduces lots of new exciting features in Angular 2 support. Combining that with support for the latest TypeScript and ECMAScript 6 (2015) features, WebStorm can be a great playground for your new Angular 2 applications.

Join us for a live webinar WebStorm: Angular 2 Tips and Tricks featuring John Lindquist on May, 11th. Register now!

In this blog post we’d like to share with you some tips and tricks that we hope you’ll find useful when working on Angular 2 apps in TypeScript in WebStorm 2016.1. We’ll have a look at:

Disclaimer: This blog post is not intended as a tutorial for getting started with Angular 2. If you’re new to Angular 2, we suggest you to go through the Angular 2 Quickstart first. While Angular 2 is still in Beta, there might be some changes in the framework that can affect the way Angular-specific coding assistance works in WebStorm.

Angular 2 and TypeScript support are also available in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Professional, and RubyMine, all version 2016.1. Make sure that you’ve installed AngularJS plugin: go to Preferences | Plugins – Install JetBrains plugins and search for AngularJS.

Let’s see what you can do with WebStorm!

Installing Angular 2

To make WebStorm understand Angular 2 syntax, we need to have Angular 2 library files in our project.

The easiest way to add Angular 2 to the project is using npm. If you don’t have package.json file in the project yet, run in the terminal opened in the application’s root folder: npm init -y

Then run: npm install angular2 --save

Tip: If you have already added a package.json file in your project, you can just right-click it in the IDE Project view and use Run npm install action.

Alternatively, you can add angular2.dev.js file as a JavaScript external library in WebStorm as described here.

Auto imports in TypeScript

One of the great advantages of using typed languages like TypeScript is that you get far more precise and intelligent coding assistance, which helps you write better code more efficiently.

To define a component in our Angular application, we use @Component decorator. It needs to be imported from the Angular 2 library.

WebStorm can import symbols from other files and modules automatically. So you can just start typing @Component or, for example, a class defined in the project and WebStorm will just take care of the import statement. By the way, imported symbols from the same module are nicely put in one import statement.

auto-import-ts

You can disable auto imports in Preferences | Editor | General | Auto Import. You can still add the import by hitting Alt-Enter on the unresolved symbol and selecting Add import statement.

If you want to import everything you need first, start typing the import statement and WebStorm will suggest the files and modules to import as well as the symbols available in them.

completion-for-imports

For all unused imports, WebStorm will show a warning. With the Optimize imports action (Ctrl-Alt-O), you can easily clean up all the unused imports and merge related import statements from the same file into one line.

optimize-imports-ng

Code completion in Angular 2 components and templates

WebStorm will provide you with code completion results for any functions, methods, and properties, as well as for Angular-specific event and property bindings and inside them.

Here are a few examples:

angular2-event

angular2-completion

Inside any template you’ll get code completion for methods defined in the component:

angular2-directive-inline

Code completion suggestions and resolve work for custom event handlers defined in the component with the @Output decorator, for example:

angular2-custom-event

If you’ve defined a variable inside the template, you’ll get coding assistance and type inference for it later in the same template.

angular2-variables

In @Component decorator we can see suggestions for available properties, such as selector or template.

angular2-method-field

Documentation lookup

With the caret on Angular 2 methods or functions, you can press F1 to quickly view documentation. You can also invoke Documentation right from code completions results.

angular2-doc

Navigation

One of the most useful shortcuts for navigating around the code is Ctrl-click (or Ctrl-B) on Windows and Linux and Cmd-click or Cmd-B on OS X – it takes you to the definition of any class, function, method, variable or component. It also allows you to jump to a different module from the import statement.

Some Angular-specific navigation includes:

  • Navigation to the file from the path in styleURLs and templateURL.
  • Jumping to the component definition (to the @Component where you have specified its name it the selector parameter) from its usage in the HTML file.
  • Navigation from a one-way binding in the component to the property defined using @Input in the component definition.

angular2-nav-to-input

Press Ctrl/Cmd-Alt-Left arrow to navigate right back to where you were.

Refactoring Angular 2 components and methods

Refactoring options available in WebStorm can be a real time saver.
For component names you can use Refactor – Rename. Press Ctrl-T on the tag or selector property in the component definition and then select Rename.

angular2-rename-component

Rename also works for custom event handlers, class names and methods defined in the component.

angular2-rename-method

Compiling TypeScript

If you don’t have a fully set-up built process for your app, you may want to try a built-in TypeScript compiler. You can read about it in our How to compile TypeScript blog post.

– JetBrains WebStorm Team

Code review in JavaScript projects

$
0
0

When was the last time you reviewed someone else’s code or had your own code reviewed? None of us write 100% bug-free code, none of us know absolutely everything, and everybody at some point has had to maintain some truly bewildering code.

Code review is a practice that helps developers help each other write better code, learn, share knowledge, and make maintaining code base easier. Performing regular code reviews in a team makes everybody better at what they do, and results in better software with fewer defects.

However, code review can also be a frustrating process – you’re used to all the power of your IDE, yet when you open up a set of changes in an average code review tool, you can’t leverage any of that. The cognitive load of having to navigate through the code in an unfamiliar way and losing all the context your IDE provides is one of the things that makes developers less keen to perform code reviews.

Luckily, there’s a tool that can help you with that: Upsource.

UpsourceCodeReviewUI

Upsource provides syntax highlighting for dozens of languages. Teams using JavaScript (including ECMAScript 6 and JSX), HTML and CSS and Java get an additional advantage: having an IntelliJ IDEA core together with its JavaScript support in it, Upsource provides server-side static code analysis just like in your IDE.

Let’s take a look at some Upsource features.

Navigation

It might seem like a trivial thing, but the ability to navigate through the code is something we simply take for granted when we use an IDE. Yet these features are often missing when we open code in a tool that is not our IDE. Upsource, however, lets you click on a symbol to navigate to the declaration.

Code Navigation

Upsource understands ECMAScript 6 imports and allows you to navigate to the imported project file also in just one click – something that you’re used to in WebStorm.

go-to-file-import

You also might want to review a change’s impact. Say, if a class, a function or a method has been modified, it would be natural to see how it affected its usages. You can see from the screenshot above that this is easily done in Upsource – clicking on a symbol gives you the option to highlight the usages in the file, or to find usages in the whole project and then navigate to them.

Find Usages

Intuitive navigation is great for a reviewer as it lets you browse through the code in a way that’s natural for you, rather than having some arbitrary order imposed on you – it makes it easier to see the context of the changes under review.

Static code analysis

There’s another IDE feature that would be extremely useful during code review – inspections. You’re probably used to WebStorm giving you pointers on where the code could be simpler, clearer, and generally a bit better. If your code review tool offered the same kind of advice, you could easily check that all new/updated code doesn’t introduce new obvious issues, and possibly even cleans up long-standing problems.

inspection-number-of-args

WebStorm plugin

The navigation and inspection features are all available in the Upsource web application. While it would be great if the app could provide everything we as developers want, sometimes we just feel more comfortable in the IDE. So that’s why there’s also an Upsource plugin for WebStorm and other JetBrains IDEs, so you can do the whole code review from within your IDE. You can install the plugin in the IDE; just go to Preferences – Plugins and search for Upsource in the JetBrains plugin repository. There’s also an Open in IDE feature in Upsource which, well, lets you open a code review in your IDE.

Conclusion

While many checks can and should be automated, and while humans are required to think about bigger-picture issues like design and “but did it actually fix the problem?”, there’s also a grey area between the two. In this grey area, what we as code reviewers could benefit from is some guidance about code that looks dodgy but might be OK. It seems logical that a code review tool should provide this guidance. Not only this, but we should also expect our code review tool to allow us to navigate through the code as naturally as we would in our IDE.

Upsource aims to make code review not only as painless as possible, but also provide as much help as a tool can, freeing you up to worry about the things that humans are really good at.

WebStorm 2016.2: Drag files into HTML and quotes style

$
0
0

Things that automate some small but really routine tasks are the best. That’s why we made possible to add links to JavaScript and CSS files and images by dragging them into the opened HTML file.

If you drag a JavaScript file, WebStorm will automatically create <script src="file_name.js"></script> tag inside the head tag in the HTML file. For CSS files it will add <link rel="stylesheet" href="file_name.css">:

drag-css-js-to-html-1600

Drag an image into a specific place inside the HTML body to add an img tag with width and height attributes:

drag-image-to-html-1600

You can configure whether you’d like to have double or single quotes in this generated code in Preferences | Editor | Code Style | HTML – Other – Generated quote marks.

That would actually also affect all quotes added, thanks to code completion, for example when you type <div class=""></div>. If you enable the Enforce on reformat option, the quotes will be replaced according to the selected style with the Reformat code action (Alt-Cmd-L on OS X, Ctrl+Alt+L on Windows and Linux).

Your WebStorm Team

WebStorm 2016.2.1 EAP, 162.1447: ui-router state diagram and bug fixes

$
0
0

We are rolling out a preview for the WebStorm 2016.2.1 (162.1447), a bug-fix update to the recently released major WebStorm update.

You can download it here and install side by side with the stable version of WebStorm or, if you have WebStorm 2016.2 installed and you’re subscribed to the EAP update channel, you should soon get a notification in the IDE about a patch update.

ui-router state diagram

With this new feature (that we were still finishing at the moment of the initial WebStorm 2016.2 release), you can see a diagram illustrating the relations between views, states and templates in AngularJS app that use ui-router. You can invoke Show AngularJS ui-router State Diagram from the Find action dialog (Shift-Cmd-A on OS X or Shift-Ctrl-A on Windows and Linux) or from the file context menu in the editor.

ui-router-852@2x

WebStorm 2016.2.1 EAP also brings lots of bug fixes and minor improvements. We’ve addressed the issue with debugging Karma tests from the IDE. The full list of addressed issues can be found in the Release notes.

Please report any issues to our tracker. Thanks!

Your WebStorm Team

 

Using External tools: ESLint autofix and React Native

$
0
0

Did you know that you can easily run many command line tools from WebStorm with just a shortcut? Well, now you do! No need to go to the Terminal, thanks to the feature called External tools. Let’s see how we can use External tools to run ESLint autofix and React Native.

ESLint

ESLint is a popular linter for JavaScript that has a great number of built-in rules and can also be extended with plugins. WebStorm’s integration with ESLint allows you to see warnings and errors reported by ESLint right in the editor, as you type. (To enable that, go to Preferences | Languages & Frameworks | JavaScript | Code quality tools | ESLint.) Unfortunately, WebStorm does not yet support ESLint autofixing functionality. But we can enable that via External tools!

Assuming that you already have ESLint installed (globally or locally) and configured the rules in your project, that should be rather easy: go to Preferences | Tools | External tools and click + to add a new tool. Let’s name it ESLint Fix.

If ESLint is installed globally, run this in the command line from the project root (where app.js is the file we want to fix):
eslint app.js --fix

So in the External tools configuration, we need to set Program and Parameters accordingly, but using specific WebStorm macros that would add the filename of the opened file and project root path:

run-eslint-fix

When passing paths, we recommend quoting them.

You can also run eslint --fix for the whole project (but then you would probably need .eslintignore file to exclude node_modules). To do that, tweak the parameters like this: --fix .

If on the other hand you have ESLint installed locally, replace the program with ./node_modules/.bin/eslint (on OS X) or .\node_modules\.bin\eslint.cmd (on Windows).

Once it’s configured, you can run the tool from menu Tools > External tools. Or, you can search for it by name from the Find action dialog (Cmd-Shift-A on OS X or Ctrl+Shift+A on Windows and Linux):

find-action-eslint

Alternatively, you can bind a keyboard shortcut to run this external tool. To do this, navigate to Preferences | Keymap, and then find ESLint Fix (or whatever you named your external tool configuration) under External Tools. Now you can bind a key to run ESLint fix just like you would with any of the built-in features.

React Native

With React Native you can build modern mobile apps using JavaScript. WebStorm offers advanced support for React and JSX, and can provide you with core coding assistance for React Native apps. React Native comes with the CLI (and we assume you have already installed it and configured your development environment), which allows you to build and run apps for iOS or Android. We can configure External tools to run react-native run-ios and react-native run-android, the two most used commands. That’s very easy, here’s an example for run-ios:

run-react-native-ios

Now type React Native in the Find action dialog to see and run the configurations. That’s it!

find-action-react-native

Using prompt

Using $Prompt$ macro in the Parameters input, you can pass some additional options to the tools, for example, a port number.

Your WebStorm Team

WebStorm 2016.3 EAP, 163.5219: ES6 object destructuring

$
0
0

Please welcome a new WebStorm 2016.3 EAP build (163.5219)! You can download it here, or if you have the previous EAP build (163.4830) from the last week installed, you should soon get a notification in the EAP about a patch update.

Better support for ES6 destructuring

WebStorm now provides better support for object destructuring. You can now easily jump to the definition from the destructuring assignment and see quick documentation and parameter info when using a function.

destructuring

For a detailed list of the issues addressed in this EAP build, please see the Release notes.

Learn more about other new features in WebStorm 2016.3:

  • WebStorm 2016.3 EAP, 163.3094: Integration with Flow; PostCSS support; Smarter Rename for TypeScript; More features in Angular CLI integration; Grouped generated files in the Project view; Option to generate an .editorconfig file; Code style option for arrow functions.
  • WebStorm 2016.3 EAP, 163.3512: Integration with Docker for Node.js apps; Bundled Fira Code font; San Francisco font is default on OS X; Flow tool window with file and project errors.
  • WebStorm 2016.3 EAP, 163.3983: ESLint autofix; Automatic detection of TypeScript version in the project; Undo commit action; Test names now available in the Go to symbol.
  • WebStorm 2016.3 EAP, 163.4396: Create new React apps with Create React App from the Welcome screen; Improvements in Angular 2 support.
  • WebStorm 2016.3 EAP, 163.4830: Integration with Stylelint; Find usages for ES6 default exports; Updates Angular 2 live templates; New inspection “TypeScript import can be shortened”.

Please report your feedback to our issue tracker. To get notifications of new EAP builds as they become available, subscribe to the EAP channel in Preferences | Appearance & Behavior | System Settings | Updates.

– JetBrains WebStorm Team

Using Flow in WebStorm

$
0
0

Flow is a static type system developed by Facebook. It introduces a syntax of type annotations for JavaScript and provides a type checking tool.

Using types in your code allows Flow to catch more errors before you run the code, but is not mandatory – Flow’s static analysis can detect some errors even without type annotations.

WebStorm 2016.3 adds integration with Flow. So if you’re using Flow in your project, you will now see errors reported by Flow in the editor, as well as in a new Flow tool window. Errors are displayed right as you make changes in your code, without having to save them. Flow can also power WebStorm’s code completion, type hints, and navigation to the definition.

Let’s have a closer look at how this all works in WebStorm.

Installing Flow

If you’re new to Flow, we recommend that you check some examples on the Flow website first and follow their installation steps:

  • Make sure that Flow is added to your project. If not, run npm install --save-dev flow-bin
  • Add a .flowconfig file to your project with flow init command.
  • For all files you’d like to check with Flow, add // @flow comment on top.

Tip: Type flow and press Tab – WebStorm will expand it into // @flow.

In WebStorm:

  • Go to Preferences | Languages & Frameworks | JavaScript in WebStorm and set language version to Flow. WebStorm will then understand Flow type annotations in your code.
  • Check that the path to Flow is specified. If it’s correct, click OK to apply settings. You’re ready to go!

As you may have already noticed, there are three checkboxes for configuring how the Flow service is going to be used by WebStorm. Later we’ll discuss the features each checkbox adds.

flow-preferences

Code analysis and type checking

Once you’re done with the steps above and have enabled Type checking, WebStorm will run a Flow server that will analyze the code you’re working on.

Don’t forget that Flow analyzes only those files that have // @flow at the top.

Any errors Flow finds will be highlighted in the editor. Hover on the error to see its description.

flow-error

All errors reported by Flow are also listed in the Flow tool window. In its Errors tab you will see only the errors for the file you’re now working on.

Click the Show all errors icon on the left-hand side of the tool window and switch to the Project Errors tab to see all errors in the project. Double-click on the error to jump to the file.

flow-project-errors

Note that disabling the checkbox Type checking in the Flow preferences will stop Flow from running.

Navigation, code completion, and type hinting

As Flow has the information about the types used in your code from the annotations and type inference, it can also provide code completion suggestions based on that. WebStorm would show them in the autocompletion popup as well as in type hints.

flow-completion

To use this, go to Preferences and select the Navigation, code completion, and type hinting checkbox in addition to Type checking.

WebStorm can also use the information from Flow for navigation actions like Go to definition.

Code highlighting and built-in inspections

With this checkbox enabled, WebStorm will use the information provided by Flow to power code highlighting and its built-in inspections. Please note that enabling this option may cause performance problems.

Your WebStorm Team


Debugging client-side JavaScript with WebStorm 2017.3

$
0
0

We have some good news for everyone who is using WebStorm to debug client-side JavaScript apps in Chrome!

The first big news is that starting with Chrome 63, you can now use Chrome DevTools and WebStorm debugger at the same time.

Second, with WebStorm 2017.3 you no longer need an additional Chrome extension to debug apps in WebStorm.

Debugging in WebStorm and in Chrome DevTools at the same time

If you’ve ever tried to open DevTools in the browser while having a debugger opened in WebStorm, or vice versa, you saw that the WebStorm debugger immediately disconnected.

That happened because both WebStorm and DevTools are using the same debug protocol that did not support multi-client debugging. For many years, this Chromium issue was one of the most popular on their tracker. Well, now it’s finally fixed in Chrome 63!

This means that now you can use both the DevTools debugger and the WebStorm debugger at the same time, having their best features at your command.

For example, you can debug your app using WebStorm where you can put the breakpoints right in the source code, and then use the DevTools Elements panel to inspect DOM and styles, or its powerful Network panel to get insights into network performance.

Debugging with Webstorm and Chrome at the same time

Stepping through the code is synchronized between DevTools and WebStorm. Once a breakpoint is hit, you can use the step and resume actions in either tool – both tools will show the execution point in the code and update the call stacks and the variables view.

Easy start with JavaScript debugger

As of WebStorm 2017.3, you no longer have to install JetBrains’ Chrome extension to debug your client-side apps in the IDE.

To debug the app, all you have to do now is create a new JavaScript debug configuration and specify the URL your app is running on. Then put the breakpoints in the code and start the debug configuration. WebStorm will open a new instance of Chrome (with the remote debugging on) and seamlessly attach to it.

WebStorm team

Using and creating code snippets

$
0
0

Code snippets, or Live Templates as they are called in WebStorm, can help you save and reuse code. This can be any code fragment that you find yourself using often – just a line of code like a method definition, or a skeleton for a whole file.

There are two ways to use a snippet: either type its designated abbreviation and hit Tab, or select it from the code completion suggestions.

What makes Live templates particularly useful is that you can customize them with variables. To move from one variable inside the template to the next one, press Enter or Tab.

Here’s an example. We’ve created and used a Live Template for a new React stateless component, in which a component name is a variable that we can specify when using the template. (We’ll talk about creating custom templates in a second.)

Simple Live Template in action

A template can have multiple variables and they can depend on each other. Here the variable for the selector name is a dashed-case version of the class name.

Live Template a-component with two variables

WebStorm has several collections of Live Templates that are available out of the box, including code snippets for development with Vue, Angular, and AngularJS. You can find then under Preferences | Editor | Live Templates.

By the way, Live Templates can be used not only in JavaScript or TypeScript, but in any language that WebStorm supports.

Creating a custom Live Template

Let’s now see how we can create our very own Live Template. For this example, we’ll create a template for an Angular component, similar to the default a-component. This is a simple one!

  1. Select the code you want to use in the template in the editor, press Cmd-Shift-A, and search for the action Save as Live Template…
    Save code as a Live Template
  2. Enter the abbreviation that you’ll be using to invoke the template. We’ll go with ngcomp.
  3. Add a template description.
  4. Optionally, add variables to the code of the template.
    Variable names should start and end with $. In our example, we need only one variable for the component name. Of course you can have multiple variables, as long as each one has a unique name.
  5. Add $END$ to where the cursor should be at the end.
    Add variables to a Live Template
  6. Click the Change link below to select the parts of code the template will be available in. For our ngcomp, we want it to be available in any part of a TypeScript file.
    Specify where the Live Template should be availbale
  7. Click OK to save the template. That’s it!

Let’s do one more, this time a little more complex.

We’ll have 2 variables: the name of the component class and the name of the component selector.

Adding a second variable to a Live Template

Logically we want to first specify the component name and only then the selector, even though the selector comes first in the code. To do this, we click Edit variables and using the arrow icons to adjust the order of variables.

Change the order of the variables in the Live Template

Now, according to the Angular Style
Guide
, selector names are usually a dashed-case version of the component name. This means we can just specify the class name in our template and get the selector name automatically through its transformation.

To do this, we click the Expression field next to the selector variable and select the function we need – lowercaseAndDash, and then add the variable name as parameter.

Add variable transformation

Let’s see our new template in action:

Custom Live Template in action

We can also select “Skip if defined” next to our selector variable. In that case, after we’ve edited the component name and pressed Enter, the cursor will go to the end position and not to the selector.

With the many functions available in WebStorm, you can do any variable transformations you need to create really powerful Live Templates. Try them out and see if they save you some time coding!

WebStorm Team

Node.js profiling in WebStorm. Part 1: CPU profiling.

$
0
0

Profiling is hard work. The amount of gathered information and demand to keep in mind the execution times and code structure is a serious challenge.

WebStorm assists you on this tough journey. It points at hot spots by opening and highlighting them in call trees. It will immediately navigate you to the related source code. The IDE can filter out “noise” by showing only functions that took lots of time. And, by the way, it will also start a Node.js application with profiling and automatically open the profile after the run.

v8-cpu-profiling-tool-window

If you’d like to immediately try the feature, start with checking Record CPU profiling info in the V8 Profiling tab in your Node.js Run Configuration.

Update: Part 2: Memory profiling is now available.

Table of content

Background information

CPU profiling is a way to look inside the code execution and see how the system lives in dynamics. Due to the Node.js IO-bound one-thread architecture, it is especially dangerous to experience a CPU-consuming callback in the event thread.

Profiling method and results distortion. As you may know, V8 is an open-source JavaScript engine developed by Google. It’s used in Google Chrome, Chromium, Node.js, and io.js.

V8 has a built-in sampling CPU profiler, which provides information about the execution of your code and the behavior of the JavaScript engine itself: garbage collection cycles, compilation and re-compilation, and code optimization. Node.js CPU profiling in WebStorm is built around the V8 profiler.

What is really important is that you need to consider the method of gathering profiling information. Sampling profilers periodically record stack traces of your application. This method does not guarantee very good accuracy: snapshots happen to be taken at random moments, the term “random” in this context meaning “independent from the application execution.”

The recorded information does not provide us with the whole picture of what happened during execution, it does not contain all called functions, and it can even distort the relative quantities of function calls. Sampling profilers can not say how many times a function was called. However, statistically this method gives results that are good enough to judge about hot spots.

Remote profiling. It is technically possible to run Node.js applications with profiling on remote machines, and work with resulting log files. This can be useful for stress testing of your application.

To do it, start your Node.js application with the following flags:

node.js --prof --log-timer-events

After the execution, open the v8.log file in WebStorm by choosing Tools | V8 Profiling | Analyze V8 Profiling Log on the main menu.

You can find more information on running the internal profiler from the command line in the V8 wiki or in this article from Chromium “For Developers” section.

It all may sound too complicated, but don’t panic! WebStorm tries to simplify the inner details for the developer: you just run the application and see the hot spots.
Here you are:

Diving into the feature details

To put in two words, use can use CPU profiling with the following scenarios:

  1. Run a Node.js application from WebStorm with CPU profiling.
    After application execution is over, the CPU profile view is opened.
  2. Open a previously recorded Node.js profiling log.
    When using scenario 1, one or several log files are created by the V8 engine. You can always open them again later.
    Also, you can record V8 profiling log on another environment (see section about Remote Profiling).
  3. Open a log file recorded by Chrome or Chromium (run with profiling flags).

To open a log file, choose Tools | V8 Profiling | Analyze V8 Profiling Log on the main menu. The parameters in the dialog are the same as in the Run Configuration described below.

Running Node.js application under profiler

Set your Node.js Run Configuration to record V8 profiling information:

nodejs-run-configuration-v8

Specify the path to the tick Node.js package — we use it to transform recorded logs into statistical CPU profiles. Tick contains V8 scripts, adopted for use with Node.js.

Gnuplot is used for timeline creation. You may omit this parameter, but then no timeline will be created. You can find more details on the installation below.

Click Run to start your application, and run the scenario that you would like to investigate.
After the application execution is finished, the CPU profile will be opened in the V8 Profiling tool window.

Explore call trees

We present the collected information in the following ways:

  • Top Calls: hot spots list (a list of actions that took long)
  • Bottom-up: first, we show hot spots together with their callers, and callers of their callers etc., i.e. a tree of callers.
  • Top-down: from entry points we unroll the execution tree down, from caller functions to callees.

The sampling profiler takes stack traces at certain interval — called tick. Therefore time in a CPU profile is presented in tick units.

The number of ticks or its ratio to the total execution time is presented as Total or Self. The Total value shows how much time was spent inside the function and the functions it called (i.e. recursively). The Self value shows how much time was spent only inside the function itself, not taking into account its child nodes.

Top Calls view

top-calls-view-cpu-profile

Here you can notice the following details:

We use text color codes to distinguish between native (JavaScript engine) actions — shown in grey, Node.js calls — shown in blue, and the user code — just of the default text color.

We use icon color codes to differentiate files: functions from the same file are shown with the same color.

You can navigate to code! We will search for files and symbols mentioned in snapshot and will try to find them in your project. We also can go inside Node.js sources and core modules and inside V8 sources (for that, just download Node.js core modules in Settings | Languages & Frameworks | Node.js and npm).

Bottom-up view

bottom-up-view-cpu-profile

Here for every method we show which ratio of its caller, i.e. its parent time it took. In the screenshot you can see how to filter the results: you can choose to see only the functions that took more than 5% of the total execution time.

Top-down view

top-down-view-cpu-profile

Here you literally get full control over the execution information.

You can see all calls as a tree. Sometimes the tree can go really deep. To help you deal with it, we show you the call tree already expanded, expanding all nodes where execution took longer than 10% (for either the Self or the Total time).

Also, on the screenshot you can see the tooltip of the Export action: you can get all these trees—Top Calls, Bottom-up, Top-down—saved as a text file!

V8 optimizer

Note the signs ~ and * before function names:

* means that the function was optimized by V8.
~ means that the function was not optimized.

Though optimization may be delayed by the engine (and is not performed for short-running code), this might point at places where the code can be rewritten for better performance. More information on the subject is available in this article.

Timeline: see the dynamics!

To work with the Timeline view, make sure you’ve specified the path to gnuplot in the Run configuration.

The Timeline view helps to find application pauses and explore the calls that provoked them. You also see garbage collection and user code execution together, in one picture.

We took the chart that V8 creates for us (for plot interpretation, please refer to the Google Chromium documentation), and added several actions to zoom into time interval or get stack traces around longest pauses.

Here is how to zoom:

timeline-cpu-profile

To see the stack frames for the longest pause, click Show in the popup appearing above the blue arrow at the bottom of the timeline:

show-timeline-cpu-profile

and get the stack traces:

stack-frames-cpu-profile

Installation and configuration information

Run Configuration/Analyze V8 Profiling Log parameters:

Log folder — the folder where v8.log files will be written.

One log file for all isolates (V8 instances) — whether to create only one log file (and (accordingly) one profiling results view) for all V8 instances or have a separate file for each instance (additional V8 instance can be created by Node.js, for example, for a debug process).

tick package — path to the tick package. This package contains V8 scripts for transformation of recorded logs into CPU profiles, adopted for use with Node.js.
Run npm install -g tick to install the tick package.

gnuplot executable — path to the gnuplot executable. Gnuplot is a well known graphing utility. It is used by V8 scripts to create timeline images.

Gnuplot installation

Windows

To install gnuplot on Windows download the installer using the appropriate link provided on the gnuplot website and then run the installation.

Linux

We recommend using APT to install gnuplot and all the required dependency on Ubuntu.
Run sudo apt-get install gnuplot-x11 in the command line.

On other Linux systems, we suggest using your package manager or downloading a .tar.gz file from gnuplot website and then following the steps in the readme file. Make sure that you also have the x11 and libgd libraries installed.

Mac OS X

On Mac OS, you can use the Homebrew package manager:
brew install gnuplot --with-aquaterm --with-x11

If you see an error message about missing png or pngcairo terminals, please check whether they’re installed with the gnuplot -e set terminal command. If the libraries are missing, we recommend reinstalling gnuplot using a package manager (APT, Brew, Port, etc).

Node.js profiling in WebStorm. Part 2: Memory profiling.

$
0
0

We continue talking about our new Node.js profiling features in WebStorm 10. In our previous post we explored CPU profiling. In this one we’ll dive into the strategies for memory problems investigation and see how WebStorm can help us apply them.

heap_profiling-cover

Table of content

Background information

JavaScript is a language with automatic memory management. That means that the JavaScript engine itself takes care of allocating space for your objects and collecting objects when they are not needed.

Node.js, io.js, and Google Chrome use the same open-source JavaScript engine, called V8.

In this article we will talk about the V8 JavaScript heap, i.e. only about the memory area that is managed by the JavaScript engine and contains JavaScript objects.

So why should we then care about memory profiling? Although memory is allocated, freed, and defragmented automatically, it is still our application code that requests object creation, and the application should indicate when objects are not needed. The application is responsible for the object lifecycle. That is why it’s important to use an optimal memory consumption strategy and, of course, watch out for errors.

Memory problems are especially dangerous for Node.js applications. Node.js servers tend to run for a long time, so any memory leaks would accumulate over time.

The three main concepts around application memory management are memory budget, memory leaks, and the speed of memory consumption. Let’s talk about them.

Memory budget

Our application operates a limited amount of memory, and big data structures such as caches or queues may eventually consume a significant part of memory. It may result in running out of memory or frequent garbage collection invocations. Taking a heap snapshot in this case will help us find out which of the queues or caches run “out of the budget.”

Memory leaks

How does Garbage Collector (GC) determine that an object is not needed? There is a special group of objects, called GC roots that are known to exist. Hence, they are used as a starting point to determine which objects can be collected.

GC roots include objects in the current call stack (i.e. referenced from the code that is executed right now), objects that belong to the JavaScript engine, such as compilation cache, and objects backed by native (non-JavaScript) objects. Garbage Collector iterates over the graph of objects (heap) starting from the GC roots, following the references between objects. Any object that cannot be reached from any GC root is garbage and subject to collection.

Memory leaks occur when objects that are not needed for the application anymore, but are still referenced from one of GC roots, tend to accumulate over time. Leaks may be small, but still dangerous due to their tendency to grow. The causes of memory leaks may include errors in application cache management, inaccurate use of closures, or keeping detached DOM nodes in JavaScript variables.

Memory consumption problems may arise if you allocate objects too frequently, forcing too-frequent Garbage Collector cycles, which in turn leads to performance degradation.

Relevant articles

We highly recommend that you read the JavaScript Memory Profiling guide on the Chrome website. There is also another great article by Addi Osmany that we highly recommend: Taming The Unicorn: Easing JavaScript Memory Profiling In Chrome DevTools.

We believe that we can also contribute to the task of memory analysis and make it easier for the developers.

WebStorm offers you the following features that can help hunt down memory leaks:

  • Taking V8 heap snapshots in the runtime,
  • Heap snapshots view,
  • Heap snapshots difference view (in WebStorm 10.0.3+).

Taking heap snapshots in WebStorm

To take heap snapshots while running a Node.js app in WebStorm, select Allow taking heap snapshots in Node.js Run Configuration in V8 Profiling tab:

node-run-config

You will need to install the v8-profiler node module, which contains the JavaScript binding for the V8 takeSnapshot() method. WebStorm generates a special proxy code, which runs the in-process server. When it’s time to take a heap snapshot, WebStorm sends this server a notification through a Communication port specified in the Run configuration.

So when the application is up and running, you can use a new Take Heap Snapshot action in the Run/Debug tool windows. You’ll be asked to select a file where the snapshot will be saved. You can choose to open it immediately:

save_snapshot

The Show hidden data check-box allows you to see internal V8 objects and hidden links.

Note: You can also take heap snapshots in Google Chrome and then open them in WebStorm.

Finding memory leaks in heap snapshots

In this article we’ll be using the Interesting kind of JavaScript memory leak example from Meteor’s blog. It’s a great case with a perfect explanation that illustrates the potential danger of closures and why we might need memory profiling.

Here is the code:

var replaceThing = function () {
  var originalThing = theThing;
  var unused = function () {
    if (originalThing)
      console.log("hi");
    };
    theThing = {
      longStr: new Array(1000000).join('*'),
      someMethod: function () {
      console.log(someMessage);
    }
  };
};
setInterval(replaceThing, 1000);

In this example the value of originalThing will be kept in the lexical scope of theThing.someMethod closure. Since originalThing gets reassigned again and again, we are going to have a chain looking like:

theThing -> someMethod -> (lexical scope) -> originalThing -> someMethod -> (lexical scope) -> etc.

Please refer to the original article for the detailed explanation.

We are going to check if we can observe the predicted situation in the heap snapshot. So let’s run the example:

  1. Create Node.js Run Configuration and select Allow taking heap snapshots.
  2. Start Run Configuration and after a few seconds record the first snapshot.
  3. Wait for about 30 seconds and record the second snapshot.

Now let’s open the first snapshot. We’ll see the Containment view:

containment_view

Containment view

The Containment view shows the relationships between objects. In the main tree GC roots occupy the first level and you can unfold objects to see their children.

If you select any object in the main tree, its details are shown below: the path to the object from one of the GC roots and all other nodes that reference this object. Usually a heap dump is a dense graph, where each object has many links to and from it. There are many cyclic references and references from system objects.

In general, the Containment view is essential for understanding why an object is not collected, i.e. who holds a reference to it.

However, we see a really huge tree with many links and internal objects so… what will our first steps be?

First of all, we can use the Search feature. WebStorm searches for objects by:

  • variable, parameter, or function name (“Link names”),
  • class names,
  • text string contents,
  • snapshot object IDs (every object inside a heap snapshot has its unique ID),
  • marks given by the user (we’ll talk about those later).

Since we expect a memory leak to occur around the inner closure and originalThing variable, let’s search for it:

search_action

On this screenshot you can also see the “artificial” groups of GC roots that are created by V8.

The search results are shown in the bottom view:

search_results_and_mark_action

We can see that there are multiple instances of the originalThing variable, each kept in a corresponding context object. So our prediction about the memory leak has come true.

Mark action

To easily differentiate same-named objects and to be able to return to them again, we can use the Mark action. The object is then associated with a text mark and can later be found via search.

You can easily navigate from the search results (and from other views) to the same object in the main tree (i.e. the main tree in the Containment view), or jump to the source code, by using context actions:

jump_to_source

Just to complete the picture, let’s see the same leaking chain starting from theThing object:

origin_of_chains

There are other ways to explore the snapshot.

Very often you have no assumptions what could be causing the leak or whether there’s a leak at all. One way to hunt for leaks is working with the Biggest objects view.

Biggest objects view

The Biggest objects view sorts objects by their retained size and shows the top list. Looking at the biggest objects might help in situations when there is a single root of memory accumulation, such as incorrectly written cache or an overflowed queue.

biggest_obj

In our case we observe many longString string objects.

In the Biggest objects view we do not see any specific links that identify the object, but there is a Details view in the bottom that shows the path to the selected object from one of the GC roots and retainers (objects that also hold the references to the current object).
You can navigate to the same object in the Containment view using the Navigate in Main Tree action.

Another way of investigating heap snapshots is to use the Summary view.

Summary view

summary_view

In the Summary view all the objects are grouped by their type. If one type dominates the view, it might point to the memory leak. You can navigate to the parent object where the objects of this type are hold (using the Navigate in Main Tree action or just by looking into the Details view) and check if it is the leak root.

Another good hint is to look at the Distance parameter for the objects of the same type (distance is the number of steps between the current object and the GC root on the main path). If objects of the same type have different distances, it means they were created by different parts of the code or with a different recursion level. This may be a clue, if you don’t expect different creation paths for objects of this type.

In our case, we see that string objects take the most space. The Different distances rule also works well in our case—we see our heavy strings are all created at different depths.

summary_view_dist

Comparing Heap snapshots

Starting with WebStorm 10.0.3, it is possible to see the difference between heap snapshots in a special view.

This feature allows you to get a clearer picture: you can concentrate more on the objects that keep reappearing or got heavier, and less on the “background” stuff.

In an ideal situation and after a long running time, Heap Diff would directly point to the memory leaks. However, you should always expect some dynamic changes between snapshots: event objects will be created, compilation and recompilation would occur in runtime, and so on.

Another idea behind Heap Diff is that it assists in analyzing slow-running memory leaks.

Suppose you have a leak that will only show up after hours of work. If you just analyze a single snapshot, other “healthy” objects might be bigger than the leak that may not have accumulated enough, making it difficult to detect the leak with the usual strategies (such as biggest objects or class groups).

With Heap Diff, you are likely to notice a memory growth sooner, since other heavy objects are likely to be filtered out.

So let’s examine the difference between the two snapshots that we took in our experiment.

Opening the Diff view

Use the Compare with action, select the second snapshot in the dialog, and specify whether it is a subsequent or previous snapshot. A Heap snapshot view for the second snapshot will also be opened in the other tab.

open_dff

Summary Diff view

In the Summary Diff we can see aggregated information about each type of objects:

  • The difference in the number of objects of each type (Count Diff),
  • The number of created and destroyed objects (Count),
  • The difference in the sum of self-sizes of objects (Size Diff),
  • The sum of self-sizes in the “before” and “after” snapshots (Size).

If you expand a type node, you will see the objects of that type that were created/destroyed with their retained sizes. (Only the first 50 objects are shown.)

This view helps locate the types which led to the biggest memory growth, or the types with overly volatile behavior, i.e. with objects that were created/destroyed too often.

summary_diff_view

Biggest Objects Diff

In the Biggest Objects Diff view, we show how the size of the objects changed and which objects were added/removed. Growing leaks that are big enough are likely to be highlighted in this view.

biggest_obj_diff

Both in the Summary Diff and the Biggest Objects Diff views, you can invoke context actions to mark objects (the mark will be propagated to the originating snapshots), or to navigate to the same object in the originating snapshot (provided that this snapshot is open).

In our case we observe that the number of strings has increased by 75% (in the Summary view) and we see the same-size big string objects added or not changed (in the Biggest Objects view).

Heap snapshots of web applications

Web apps also leak. Since Google Chrome and Node.js have the same JavaScript engine, you can take a snapshot in Chrome for your web app and open it using WebStorm: Main menu | Tools | V8 Profiling | Analyze V8 heap Snapshot.

Of course, Chrome has its own support for working with heap snapshots. Give WebStorm a try and tell us if our new features for searching by object names, navigation inside a snapshot, and navigation to code were useful and where we are missing something!

Web apps snapshots have a more complicated structure. There is one more player on the scene: the DOM tree. So there are typical leaks related to patterns of working with DOM objects in JavaScript.

The most well-known leak is keeping a reference to a DOM object detached from the document in the JavaScript code. You can find such objects under the Detached DOM trees synthetic GC root, marked with yellow or red.

Here’s a an example of a heap snapshot taken for the website (here it’s bbc.com) opened in WebStorm:

bbc

Taking heap snapshots in remote environments

In case you want to hunt for memory leaks somewhere other than the local environment, you can use a programmatic way of taking snapshots. Follow the instructions in v8-profiler module description and then open the taken snapshots using Main menu | Tools | V8 Profiling | Analyze V8 heap Snapshot.

Caching snapshot data

Analyzing a heap snapshot takes WebStorm a significant time. However, once a snapshot is analyzed and opened, you can return to it quickly: all indexes are kept in the IDE system directory.

Conclusions

The example that we’ve investigated throughout this article perfectly illustrates that even if a piece of code hardly raises any suspicions at first sight, it can cause big problems with memory due to internal references. The bottom line is that heap profiling is essential for JavaScript applications.

Memory monitoring and profiling is not a straightforward task. We on the WebStorm team believe that some of the features we provide in WebStorm will help you avoid memory leaks in your project and will save you time. We will continue to improve the heap introspection features.

Thank you for reading. Your feedback is welcome!

WebStorm 11 Early Access Program

$
0
0

We are starting the Early Access Program for WebStorm 11, our next major release. Go ahead and download WebStorm 11 EAP now!

UPD: Read about the new features added in the next EAP build:

  • WebStorm 11 EAP, 142.3805: improved HiDPI support for Windows and Linux, clickable links in comments, breadcrumbs in Stylus files.
  • WebStorm 11 EAP, 142.4148: encode HTML special symbols, improvements in Meteor support, TypeScript 1.6: intersection types and type guard functions.
  • WebStorm 11 EAP, 142.4723: code style for chained methods, React and TypeScript 1.6 support improvements.

What is the Early Access Program? It’s how we make our development process more transparent and share with you our progress on the new IDE features. By taking part in WebStorm 11 EAP, you can try some of the new features months before the public release, and hopefully provide your valuable feedback that will help us improve the IDE for you. The EAP builds are free and can be installed side-by-side with your stable version of WebStorm.

ws11eap-splash

Please note that EAP builds are pre-beta software and may contain issues, which we ask you to report to our issue tracker.

Improvements in TypeScript support

We are working hard on improving TypeScript support. First of all, we now bundle just-released TypeScript 1.5 (actually 1.5.3) compiler with WebStorm, which brings support for features like ES6 modules and decorators to TypeScript:

ts-imports-and-decorators

 Second, WebStorm now understands the scopes defined in the tsconfig.json file and uses them for coding assistance. If the class you want to use is missing from the files property in tsconfig.json, a quick-fix will help you add it to the tsconfig.json file:

tsconfig-and-compiler

You can also select Enable TypeScript Compiler if you’d like to use tsconfig.json with the built-in TypeScript Compiler.

Next up is integration with TSLint, a linter for TypeScript, as its name suggests. You can enable that in Preferences | Languages and Frameworks | JavaScript | Code quality tools. Then you’ll start seeing warnings from TSLint right in the editor, if any.

Last but not least, TypeScript support gets a very handy auto-import feature that suggests adding an import statement when you reference a class:

ts-auto-import

Yeoman integration

Yeoman integration is something we’ve wanted to implement for a while and we’re excited that now finally you can access hundreds of project generators right from the Welcome screen.

Make sure that you have Yeoman installed. Click Create new project, select Yeoman from the list on the left, search for the generator you need, and then follow the steps suggested by the generator.

run-generator

As we’re still working on UI improvements, we would be happy to hear your feedback on what is already available.

JSX support improvements

We’ve introduced lots of general improvements in JSX support. For example, WebStorm now understands React components declared as classes and ES6 imports. And you finally have completion available for closing tags.
Here’s the full list of addressed React support issues in our tracker.

New inspections: Missing require() call and Missing module dependency

We’ve added two new inspections to help you work with Node.js apps.

The first one suggests adding a missing require() call for the modules you use further in your code (in case you forgot to do that). It can be a node module installed in your project’s dependencies, or a module somewhere in you project:

insert-require

Another inspection suggests adding a module to the dependencies or the devDependencies section in your package.json file, if you have required a module that is available on the npm:

add-to-packagejson

Are we missing anything? Let us know what you think.

Debugging Webpack projects

In WebStorm 11 EAP we support source maps generated by Webpack, a module bundler that is seeing wide adoption lately.

Thanks to these source maps, the WebStorm debugger can stop on the breakpoints put in the source files, while the compiled app is actually executed in the browser. However, because of the complexity of the build process in some cases and a variety of implementations of source maps in different module loaders and tools, WebStorm’s “magic” that makes the matching between the source code and executed code doesn’t always work.

If WebStorm hasn’t resolved paths in the source maps for your app, we encourage you to explicitly configure mappings from the remote URL of the compiled script to its local path in the debug configuration (for example, http://example.com -> /build).
In case of Webpack, you should also map the URL of the source (listed in a source map) to the local path (for example, webpack:///.-> <project dir>).

We’ll talk about this in more detail in a follow-up blog post.

Running a single Mocha test

If you’re using Mocha for unit testing, you’d be pleased to know that now you can run a single test from the IDE.

mocha-run-single-test

Simply right-click on the test name in the test file and select Run or Debug this test. A new Mocha run/debug configuration will be automatically created, which you can run again later using the Run…/Debug… action.

Flame charts in Node.js CPU profiler

A new flame chart view is now available in V8 CPU profiler. It’s a visual representation of your Node.js app execution. It might help you notice the functions that took the most CPU time and then explore them further.

flame_chart

You can read about Node.js CPU profiling with WebStorm in our previous post.

Navigation to injected dependency definition in AngularJS 1.x and ngDoc

Now you can jump to the definition of the injected object in AngularJS:

angular-inj

For ngDoc @example tag, now you get code highlighting and assistance:

ngdoc-example

Dart support enhancements

Dart developers can benefit from support for null-aware operators, support for package resolution configuration file (.packages) introduced in Dart SDK 1.12, a better code formatter, and many different bug-fixes.

Improvements in the core platform

Adjust code style settings as a quick-fix

Configuring your code style just got easier. Select a code fragment, press Alt+Enter and select Adjust code style settings to see and adjust the code style settings that can be applied to this code with the live preview. No need to scroll through the long list of all available code style settings. Once you make the adjustments, they are saved in your current code style scheme and the file is reformatted.

adjust_code_style

Preview for Find in path

A new Preview tag is now available in the Find in path dialog. It shows the first 100 results in real time, so you can find what you need more quickly and easily.

Other changes include:

  • Support for Mercurial queues
  • Opportunity to edit a diff in the commit dialog

Custom JDK status update

As you may know, we’ve been working on a custom build of JDK 1.8 for our OS X Yosemite users. There have been some performance issues that we’re fixing, while not compromising the font rendering. As we continue working on performance improvements, please let us know if you notice any problems with the scrolling. Your feedback is very helpful and much appreciated!

Please note that EAP builds do NOT require an active license and can be used for up to 30 days. To get notifications of new EAP builds as they become available, subscribe to the EAP channel in Preferences | Appearance & Behavior | System Settings | Updates.

You can look though the full list of the web-related issues addressed in this build on our tracker.

You can download and install WebStorm 11 EAP (build 142.3470) right now. Please submit your feedback in our issue tracker.

Develop with pleasure!
– JetBrains WebStorm Team

Webinar Recording: WebStorm – Things You Probably Didn’t Know

$
0
0

The recording of our July 23 webinar with Hadi Hariri, WebStorm – Things You Probably Didn’t Know, is now available on JetBrains YouTube channel.

In this video, you will learn lots of tips and tricks about how to work efficiently when doing web development in WebStorm. Whether you’re working with plain HTML, CSS and JavaScript, or using one of the many frameworks and libraries that WebStorm supports, you’re bound to learn some new things you probably didn’t even know existed.

Hadi covers a wide range of topics including Navigation around the project, Code editing, Code analysis, Code style and many others. During his demo he uses keyboard shortcuts extensively so that you can also pick up some new useful key bindings.

Here are a couple of links that cover some of the things mentioned during the webinar:

If you have any questions, please feel free to ask them in the comments below.

And here’s a short Q&A section based on the questions asked during the webinar:

Q: When I’m using only one editor tab, can I undo and redo changes in any of the files?
A: Sure, WebStorm keeps track of all your changes. You can go back to any file you’ve edited before and undo the change. You can also do that using the Local History feature – right-click on the file, select Local History, and you will see the whole history of your recent changes with the option to revert them. Call Local History on the project root to see all recent changes in the project.

Q: I would like some tips on working with Git from the IDE.
A: Unfortunately, we were not able to cover VCS integration in this webinar. Watch one of our past webinars on using VCS (including Git) in IntelliJ IDEA-based IDEs.

Q: Is there a master list of all the keyboard shortcuts?
A: You can find the default keymap by going to Help | Default Keymap Reference. The complete list of shortcuts is available in Preferences | Keymap. From there you can search the shortcuts by action name, or search actions by the shortcut. Read more about shortcuts in this blog post.

Q: How can I access the Productivity Guide mentioned during the webinar?
A: The Productivity Guide is available via the Help menu. It shows you the IDE productivity features that you’ve already tried as well as those you have yet to discover.

Q: As a relatively new user of WebStorm, I like these type of webinars that show off new feature, how-to’s, and other advanced tips. I feel that I only use a small portion of WebStorm and need to be exposed to the rest of the product.
A: Check out our previous videos and webinars covering new IDE features:

You can also find lots of feature-specific videos on our YouTube playlist.

Develop with pleasure!
– JetBrains WebStorm Team

Accessibility features in WebStorm 2018.3

$
0
0

In this era of software development, professionals everywhere are paying more attention to diversity, including building software with accessibility in mind. WebStorm contains a multitude of features to help make accessible software, and adds more in every release.

Developing for those with accessible needs is important for the following reasons:

  • When you make it easier for someone with accessible needs to use your software, it makes it even easier for those won’t don’t have those same needs. It’s a win-win.
  • According to Forrester and Microsoft’s research, up to 60% of the population has accessible needs that may result in the use of accessible technology.
  • An aging world population demands that software and technology evolve with their users.

There are four main facets of developing with accessibility in mind to consider:

  1. Visual: Blindness, low vision, color blindness, color contrast sensitivity.
  2. Auditory: Deafness, low hearing.
  3. Motor: Tremors, injury, loss of limb, aging, arthritis, and many debilitating diseases and medical issues.
  4. Cognitive: ADHD/ADD, dyslexia, autism spectrum, synesthesia, learning disabilities, and similar.

These facets cover the range of human characteristics and abilities, and web apps need to account for this wide human spectrum. Otherwise, the research shows that your web app could be unusable to a large number of your customers.

There are many design and programming techniques available for developing with accessibility in mind. This article covers a few of the basics that were released in WebStorm 2018.3.

Develop highly accessible websites and apps

WebStorm enables developers to write more accessible code that adheres to Web Content Accessibility Guidelines (WCAG). By enabling you to write better, well-formed, semantic HTML, WebStorm assists in accessible development, since screen narrators and other accessible devices rely on HTML that is precise. The introduction of semantic HTML in HTML5 was meant to provide a clear context to accessible devices so they can translate pages better.

You can review and add attributes required for accessibility into their respective elements. For example, pressing Alt-Enter on the html element allows you to insert a missing lang  attribute, or a missing alt attribute on an img element.

20813-accessibility-html-lang

Accessible tags and attributes in the page head are often overlooked, since that section of HTML isn’t frequently written as it’s usually part of a framework template. But WebStorm can offer a friendly reminder to add in elements such as the title. The title tag is a necessary element for screen narrators to announce to the user what they can expect from this page.

Insert the title tag between the head tags so narrators can infer the page contents

Filling in forms on web pages is often a challenge for accessible users. Many accessible users require alternative input devices, and others struggle with badly designed HTML forms. To better design forms that are accessible to everyone, keep the following tips in mind:

Wrap fieldset tags around a group of related items in a form such as radio or checkbox  elements by using Cmd-Alt-T/Ctrl-Alt-T to invoke Surround With feature. Don’t forget the legend tag so that a screen narrator will announce the purpose of the items.

Use the legend and fieldset tags to wrap related items so assistive devices can determine what they are

A new feature in WebStorm 2018.3 automatically displays a quick-fix when you need to add a missing label element to correspond to an input or textarea. Alternatively, you can press Alt-Enter to add the label. Screen readers use the label tag to determine the context and content of forms, so the accessible user can properly enter the information.

Use the label element to supply information about its corresponding input element

WebStorm has features for developers with accessibility needs

In addition to helping developers create more accessible software, WebStorm contains features to help developers who have accessible needs to write software more easily. In Settings/Preferences, under Appearance and Editor, you can customize the themes and visual aspects of WebStorm, such as the high contrast theme and font settings.

WebStorm offers a high-contrast theme for the visually impaired

You can find more accessibility settings such as color adjustments for protanopia and deuteranopia under Settings/Preferences – Appearance. Additionally, you can set up a screen reader for use with WebStorm by following the instructions in our documentation. Everything you need for accessibility in WebStorm can be found in Settings/PreferencesEditorInspection: HTML – Accessibility.

Resources and more information on accessible web development

Accessibility is an important aspect of web development, so you’ll want to have as many tools at your disposal as possible. Here are a few of our recommendations:

  • Google Developers | Accessibility has tools and information about developing accessible websites.
  • WebAIM (Center for Persons with Disabilities) is the go-to location for all things accessibility. Here you’ll find checklists, articles, guidelines, tools, and resources to assist in your development efforts.
  • WCAG (Web Content Accessibility Guidelines) are guidelines from the W3C recommendations on how to make web applications more accessible.

This article has outlined just a few minor tips for developing with accessibility in mind. Keep an eye out for more information from us about accessible development in the future such as working with HTML forms, and ARIA attributes, as well as accessibility and JavaScript.


Featured plugin: JS GraphQL

$
0
0

The JS GraphQL plugin is one the most popular plugins for WebStorm, IntelliJ IDEA, and other JetBrains IDEs, and we are very excited about the release of its second version

In this blog post we’ll have a closer look at the updated plugin and how it can help you work with GraphQL in your JavaScript apps.

We want to thank Jim Meyer, the author of the plugin, for the amazing work he has done to build this plugin!

Working with schema files

The plugin brings full support for the GraphQL Schema Definition Language (SDL). That means your .graphql file will include syntax highlighting, and as you start typing, you will get suggestions for the keywords and built-in and custom types, as well as interfaces and enums.

Completion in schema file

Cmd/Ctrl-click the type name to navigate to its definition.

The plugin will check that all the types you’ve used are defined somewhere in the file, and it will show an error message if they’re not. Press Alt-Enter to fix the problem with one of the available quick-fixes.

Quick fix in schema file

All the familiar features like commenting, folding, brace matching, formatting, quick doc, as well as Find usages and Rename work for the GraphQL schema language.

If your schema is described in the template string in the .js or .ts file, you can use a tagged string (const typeDefs = graphql). Or you can press Alt-Enter and then select Inject language – GraphQL to enable coding assistance.

GraphQL in JavaScript

Working with queries and mutations

When you write GraphQL queries or mutations inside template strings in your JavaScript or TypeScript files, you will get full schema-aware code completion for types, fields, and arguments. Cmd/Ctrl-click will take you to the definition in the schema file and if you press F1, you can see the quick documentation for the symbol.

Completion for GraphQl in JavaScript

Find usages and the Rename refactoring will also work as you would expect them to.

Describing the environment

For the information about your development environment, the JS GraphQL plugin relies on the .graphqlconfig file. In this file you can specify the GraphQL endpoints, the location of the schema file, as well as the files included and excluded from the scope of the schema.

If you have a more complex project with multiple schemas, you can create separate .graphqlconfig files (New… – GraphQL Configuration File) in each part of your app to configure them.

The GraphQL tool window displays information about your schemas and endpoints based on these configuration files. It will also show any errors after running a query against the endpoint.

qraphqlconfig and tool window

Configuration recipes

In the graphql-config-examples repository, you can find recipes describing how to use the .graphqlconfig files to set up different types of projects that use GraphQL, including an Apollo full-stack app and a Relay app.

Doing introspection

Once you’ve specified the endpoints for your GraphQL server in the configuration file, you can now run introspection – it will ask the server to generate the schema and provide information about what queries it supports. The result of introspection will be saved in the file specified in the schemaPath file in .graphqlconfig.

To run introspection, double-click the endpoint in the GraphQL tool window and select Get GraphQL Schema from Endpoint (introspection).

Run introspection

Running queries

If you want to run a query for a specific endpoint, you can do it easily. What you need is a file with a .graphql extension (it can be a regular file in your project or a temporary scratch file) in which you can write your query. On top of the file, select the endpoint that you want to use to run your query, and then click the green icon to run it. You’ll see the result in the new Query result tab in the GraphQL tool window.

Run GraphQL query

You can also create a new scratch file for your query from the tool window – double-click on the endpoint and select the corresponding action.

To install the JS GraphQL plugin, go to the IDE’s Preferences/Settings | Plugins – Marketplace and search for JS GraphQL.

The plugin is open source and available on GitHub, where you can also submit any bug reports and feature requests. Your contributions to the plugin and its documentation are very welcome!

Using Angular 9 in WebStorm

$
0
0

Note: In WebStorm 2020.1 onwards, support for the Ivy metadata is enabled by default. See this blog post for more information.

A long-awaited update of the Angular framework, Angular 9, was finally released last week! If you’ve closely followed the news about this update, you might already know that it comes with a number of great enhancements, with the most exciting of them being the new default compiler and runtime, Ivy. To help you work with Ivy and other Angular 9 features, we’ve added support for them to WebStorm. Let’s see how you can make use of it.

Creating a new project and updating to version 9

The fastest way to create a new Angular 9 project is to click Create New Project on the welcome screen and select Angular CLI from the list of available projects. When creating a new Angular project, WebStorm will use the Angular CLI installed globally on your machine or get its latest version via npx:

creating-new-angular-project

With npx selected, WebStorm will generate a new Angular 9 project with all the required configuration files and dependencies as soon as you click Create:

new-angular-9-project

In an Angular 9 project, you can use the features you’d typically expect when working with Angular in WebStorm, such as code completion and auto imports in TypeScript and template files, all available and requiring no configuration. However, there’s one exception, local libraries, which we’ll cover in a second. And, of course, you can get all the benefits provided by the Ivy compiler, such as faster compilation, smaller bundle size, and improved type checking, to name but a few.

If you’d like to update an existing project to version 9, the best option is to do so by following the detailed instructions from the official Angular website.

Enabling Ivy metadata support in WebStorm

Angular 9 brings a new approach of defining additional metadata in .d.ts files, instead of the infamous .metadata.json. Thanks to this new approach, WebStorm can provide you with even faster code completion and inspection results. However, as some of the parts of the new standard are still being polished, we don’t have it enabled by default for now. This is likely to change later depending on user feedback, our own testing results, and changes on the Angular side.

Let’s see how you can turn Ivy metadata support on in WebStorm for even faster code insight. First, press Cmd/Ctrl-Shift-A, type Registry in the Find Action popup and select it from the search results:

looking-for-registry-in-find-action

Next, you’ll see the Registry dialog. Start typing angular.enableIvyMetadataSupport, and you’ll see the corresponding registry key. Tick an empty box next to this key and restart the IDE in order for the change to take effect:

enabling-ivy-metadata-support

Voila! Support for Ivy metadata has now been enabled.

Working with local Angular libraries

If your project uses local libraries created with ng generate library, in Angular 9 they are set to compile with Ivy by default. To get code completion for them, you need to enable Ivy metadata support. However, this metadata lacks information about some code constructs, such as @Attribute annotations or ng-content selectors. While this information is not required by the Ivy compiler, it is needed for the IDE to provide you with completion suggestions and code inspections. So, if you use any of the mentioned constructs in your local library, we recommend switching Ivy off for it. You can do this in the tsconfig.lib.json file of a specific library by adding enableIvy: false under angularCompilerOptions as shown below:

setting-ivy-to-false

Using Angular schematics

Finally, you can use schematics with Angular 9 just like you could in the previous framework versions. To do so, look for Schematics using the Find Action popup (Cmd/Ctrl-Shift-A) or select Angular Schematic… from File | New in the main menu:

schematics-with-angular

That’s about it. If you have any questions or feedback, please don’t hesitate to post them in the comments below.

The WebStorm team

Introducing the Learning Plugin for WebStorm

$
0
0

Every so often, we get some feedback about the lack of up-to-date, comprehensive learning resources for WebStorm. For new users, this scarcity can result in a steep learning curve during the onboarding stage. For existing users, it means a lack of content that would help them further excel at what they do.

Regardless of which group you’re in, we’ve got some good news for you: We’ll be releasing new educational materials throughout the year in order to address this problem.

The first of these resources is the learning plugin for WebStorm. Let’s see why you may want to download it and take a look at how to get the most from it.

First things first: who’s the plugin for?

With the help of the learning plugin, you can interactively learn how to execute some common tasks, such as refactoring code, navigating through projects, running unit tests, and more. The plugin includes a short training course divided into several modules, each with a number of lessons that teach you how to do a specific task. There is no need to go through all the lessons – you can choose to do only the ones you find most relevant.

This plugin will be most useful for those who are new to WebStorm. However, if you’re an experienced WebStorm user and feel like checking whether you know all the basic shortcuts, feel free to try it out. We’d be happy to learn whether the information in the training is at all helpful to users already familiar with WebStorm.

Installing the plugin and starting to learn

To install the plugin, go to Preferences/Settings | Plugins and search for IDE Features Trainer.

Once the plugin is installed, restart the IDE and you’ll see the new Learn WebStorm option on the welcome screen. To get started, click on it.

welcome-screen-with-learn-webstorm

Next, you’ll see the Learn tool window, which includes all the available modules and a link to the survey for sharing feedback.

learn-tool-window

To start learning, click on a module you find interesting. You’ll automatically be redirected to the task for the first lesson, or, if you’re resuming learning, the task where you left off.

code-editing-lesson

Getting the most out of the plugin

Let’s briefly review the structure of the training course. It comprises three modules:

  • Editor Basics. By taking five short lessons in this module, you can learn how to save time on common tasks. You’ll find out how to use code completion and refactorings, edit code with multiple carets, quickly navigate through projects, and more. If you only have time for completing one of the three modules, we recommend considering this one.
  • WebStorm Debugger 101. This module will give you an overview of how to run and debug programs with Node.js in WebStorm. It’s most useful for those who have previously used the debugging capabilities of other IDEs and would like to know how the debugger in WebStorm is different.
  • Getting Started with Testing. This is the shortest module, consisting of only one lesson. It explains the fundamentals of unit testing in WebStorm using the popular Jest framework as an example. You’ll find this module interesting if you plan to do unit testing in WebStorm.

The training format we’ve decided on may take some bit of getting used to, and there are some technical limitations that we’re planning to eliminate. For a better learning experience, we’d recommend keeping in mind the following tips:

  • When working through some lessons, you’ll see information about how a specific functionality related to the main topic of the lesson works without being prompted to try it out (e.g. different ways to step through code when talking about the debugger). If you’d like, you can test how the described functionality works and then undo your last action by using the default OS shortcut (Cmd+Z/Ctrl+Z) to move on with the lesson.
  • If you’d like to start a lesson over from scratch, you can click on its name below the training instructions. This will reset your current progress.
  • In some lessons, you’ll have to work with dialogs that may prevent you from looking at the training instructions, especially if you’re doing the training on a device with a smaller screen (13-inch or less). Feel free to adjust the size of these dialogs, or you can drag and drop them to a more convenient place.

We encourage you to share your feedback with us! Just leave a comment below or fill out this survey. We’re also excited to note that a few more helpful resources are coming soon, so please stay tuned!

The WebStorm team

The WebStorm Guide: A Quick Way to Learn Something New

$
0
0

We’re happy to announce the WebStorm Guide – a central place for tips and tricks on how to use WebStorm efficiently. We hope it helps you be more productive and write high-quality code without requiring you to spend too much time away from the projects you’re working on.

Explore the WebStorm Guide

So, what’s this WebStorm Guide all about? We’ve collected the tips we had posted on Twitter, expanded them with some extra information, and organized them into two categories: Topics and Technologies.

webstorm-guide-tip

Let’s take a look at each.

  • Technologies. Let’s imagine that you’ve found a tip about WebStorm’s powerful React support and caught yourself thinking, “I didn’t know that, I wonder what other React productivity boosters I’ve missed?” If this sounds familiar, the Technologies section of the guide is just for you. All the resources in it are organized into groups of specific technologies, such as popular frameworks, libraries, and the like.
  • Topics. Sometimes you come across a useful tip on how to do a specific job in the IDE, such as how to add a conditional breakpoint when debugging, and you want to dive deeper into that topic. To help you do that, we’ve also grouped the resources by topic. Each topic has a brief explanation and a list of relevant resources.

Right now, there aren’t so many tips in the Guide. However, we plan to add new ones periodically if we see that it brings value to our users.

The WebStorm Guide is also an open project, with a repository in GitHub that hosts all the content. We write all the content in Markdown and use GatsbyJS to render a static site. If you’d like to contribute to it, please refer to the README for more information.

We encourage you to share your feedback with us! Just leave a comment below or fill out this short survey.

The WebStorm team

Plugins for WebStorm You Need to Know About

$
0
0

With WebStorm, you can get straight to work without installing any additional plugins – all the core functionality will work out of the box. But what if you want your coding tool to feel a bit more personal or need some extra functionality? Thanks to the wonderful folks from our community, we’ve got a bunch of plugins that can help with that!

In this blog post, we’ll take a look at some of the handiest plugins that have been developed for JetBrains IDEs. All of these plugins are compatible with other JetBrains IDEs, like PhpStorm and IntelliJ IDEA Ultimate, and can be installed from Preferences/Settings | Plugins. Of course, it’s not an exhaustive list of all the plugins available as there are hundreds of them in our repository. If there is a plugin you like that we haven’t mentioned here, let us know what it is in the comments.

Theme plugins

Looking for something a little more you than the default IDE themes? There’s a variety of custom themes that you can choose from. The most popular themes include Material Theme UI, One Dark, Gradianto, and Dark Purple. If none of the existing themes suit your needs, you could also create your own.

switching-themes

Once installed, the theme will be available in the Theme dropdown menu under Preferences/Settings | Appearance & Behavior | Appearance.

Key Promoter X

While becoming keyboard-centric can greatly increase your productivity, it’s never been easy to get used to all the new shortcut combinations. The Key Promoter X plugin helps make this process a lot less daunting. When you use the mouse on a button inside the IDE, it shows you the keyboard shortcut you could’ve used instead. For buttons that don’t have a shortcut, the plugin suggests assigning one. All this helps you rely on the mouse less and less so you can eventually code faster.

key-promoter-x

Rainbow Brackets

This plugin color codes each pair of brackets, which can help you if you’re struggling to identify where each code block starts and ends.

rainbow-brackets

With default colors, the plugin works better in a combination with dark themes. If you’re using a light theme or want to experiment with the defaults, you can create your own color scheme. You can do it in Preferences/Settings | Editor | Color Scheme | Rainbow Brackets.

Indent Rainbow

This plugin is like Rainbow Brackets but for indents. Its main goal is to make indentation more readable. If the wrong indentation is used, the plugin will highlight the line in red, helping you find indent problems faster.

indent-rainbow

Just like with Rainbow Brackets, the default colors work better with dark themes. You can play around with the opacity of the indent colors in Preferences/Settings | Other Settings | Indent Rainbow and make it more suitable for light themes or your specific needs.

Nyan Progress Bar

Want to make your progress bar look a little bit nicer? The Nyan Progress Bar plugin can help you with that.

nyan-progress-bar

If you don’t like Nyan Cat but still like the idea of customizing the progress bar, there are a couple of alternatives available, such as Hadouken and Duck Progress Bar plugins.

String Manipulation

If you need support for advanced text manipulation actions like switching from camelCase to kebab-lowercase, the String Manipulation plugin is what you’re looking for. You can find more information on the supported actions here.

string-manipulation

Quick File Preview

This plugin can help you speed up the process of browsing through the content of each file. Specifically, it allows you to preview project files in the editor whenever you select them in the Project view.

quick-file-preview

Atom Material Icons

Want to brighten up your theme with more colorful icons? The Atom Material Icons plugin is here to help.

atom-material-icons

As an alternative, you can also try the Extra Icons plugin out. However, bear in mind that it comes with support for fewer JavaScript-related icons.

AceJump

If you feel like experimenting with navigation features, you can try the AceJump plugin out. It lets you jump to any symbol in the editor with just a few keystrokes. To learn more about how this plugin works, explore the detailed usage instructions available here.

acejump-plugin

IDEA Mind Map

Like organizing your ideas with mind maps? Then you may find the IDEA Mind Map plugin useful as it lets you create and edit mind maps represented by MMD files.

mind-map-idea-plugin

Randomness

If you’re always getting stuck coming up with some random data for your project, then this plugin is just for you. It allows you to insert random numbers, strings, and UUIDs.

randomness-plugin

To insert random data, press Alt+R and choose the type of data you want to insert. A different value will be inserted each time you use the action.

Presentation Assistant

Need to present at company events, record screencasts, or do pair programming? Install the Presentation Assistant plugin which displays the shortcuts you’re using and makes it easier for the audience to follow along with your actions.

string-manipulation

That’s it from us today. What are your favorite WebStorm plugins? Share your thoughts in the comments below!

The WebStorm team