5 posts tagged

Tips

Quick Add React Component to Webstorm

Boris Dinkevich

One of the better practices in React is breaking our view to as many reusable components as possible. To make the test a bit easier, we can set WebStorm to auto generate React Component files.

Setup

  1. Open WebStorm
  2. Click Ctrl+Enter
  3. Select “Edit File Template”
  4. Click green + on left top
  5. Name it “React Component”
  6. Set extension to: “js” (or “jsx”)
  7. Click “enable live templates”
  8. Paste this to main edit view:
#set ($clean = ${StringUtils.sub(${NAME}, "_", "-")})
#set ($component = ${StringUtils.removeAndHump(${clean}, "-")})

const $component = () => (  
  #[[$END$]]#
);

export default $component;

Usage

Anywhere in WebStorm where file adding dialog pops-up (e. g. Ctrl+Enter) you can now select “React Component”

Set the name of the file (both “-” and “_” are supported) and viola – a new Dumb ReactJS ES2015 compatible component is created.

const HelloWorld = () => (  
  <h1>Hi</h1>
);

export default HelloWorld;

Summary

This is just a small taste of what WebStorm’s file creation and Live Templates can do. Do explore more.

React   Tips   WebStorm

Browser Console Tricks #2

Ilya Gelman

Browser console is a powerful tool, and sometimes we are not aware of its features, despite our every day use of it. Let’s go through some useful tricks that can make you a bit more productive.

$0 – last inspected element

Have you ever wanted an easy way to check the scope of an element without any plugins? Try this trick: right-click on the wanted element and choose Inspect element option.

Then go to the console and paste this:

angular.element($0).scope();

$0 is a global variable with a reference to the last selected DOM node.

Browsers can remember up to five last inspected nodes, which will be stored in the global variables $1, $2, $3, $4 respectively.

$_ – last output

Sometimes you want access to the last output from the console. It is stored as $_ global variable.

Output as global variable

Let’s say, you want to assign the last output as a global variable, to play with it in the console. You can easyily do this by using what we have just learned:

var temp = $_;

But what if you want to assign some value before the last output? There is a way to do that, by right-clicking the wanted output and selecting Store as global variable option:

After that, a global variable named temp1 will created. You can store as many things as you want, they will be stored in variables temp2, temp3, and so on.

Displaying array of objects

If you build JS applications, most probably you have worked with array of object and array of arrays. But did you know that there is a supercool way to display an array of objects or arrays in console?

Try this:

var users = [  
  {
    name: "Alice",
    email: "[email protected]",
    age: 26
  },
  {
    name: "Bob",
    email: "[email protected]",
    age: 28
  }
];

console.table(users);

Copy to clipboard from JS

There is another small trick you can use for debugging. Let’s say you have two objects and you want to diff between them in some diff-viewer.

You may find copy() command useful for this. It can be used from the console to copy global variable. This is often used together Store as Global Variable trick.

copy($_);

Do ⌘/Ctrl +V anywhere and see the object you have just copied.

There is more!

Don’t stop here. If you want to find out more cool things, you can read about script blackboxing or console.assert() command.

Happy coding!

Productivity   Tips   Tools

UI-Router And Case-Sensitive URLs

Ilya Gelman

If you’ve ever encountered a situation where your URLs suddenly redirect to 404 when typed in all uppercase (if you haven’t, you should check your application for this issue anyway, because sometimes users do weird things like that), there is a simple solution.

Starting with version 0.2.11 of ui-router, you can make urls case insensitive with one config line:

angular.module('App').config(function ($urlMatcherFactoryProvider) {  
    $urlMatcherFactoryProvider.caseInsensitive(true);
})

$urlMatcherFactory also includes a number of interesting features, such as strictMode, which makes ui-router not match trailing slashes in urls. Check out these features in the ui-router docs.

Read docs, have fun!

AngularJS   Tips

AngularJS Quick Tip: Catch Internal Exceptions

Nir Kaufman

We don’t like to see our console painted in red. But when AngularJS throw an exception, we can’t catch it unless we patch the source code (and we don’t want to it). So how can we catch Angular internal exceptions?

Peeking into the AngularJS source code reveals that every try/catch block delegates the error to a service called $exceptionHandler.

example (line 20587):

this.$$writeModelToScope = function() {
    ngModelSet(ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };

In production, we usually don’t want these errors to appear in the client console. Instead, we prefer to send them to a log server for further analysis (for example). To do this, we can use a decorator method to override the $exceptionHandler service, and delegate the error to our own service for further handling.

The decorator will look like this:

(function () {
    /**
     * override the core $exceptionHandler service
     *
     * @desc decorate
     * @param $delegate
     * @returns {Function}
     */
    function exceptionHandlerDecorator ($delegate) {

        $delegate = function (excpetion, couse) {
            // delegate to your own service
            console.log(excpetion, couse);
        };
        return $delegate
    }

    /**
     * register a decorator
     * @param $provide
     */
    function utilModuleConfiguration ($provide) {
        $provide.decorator('$exceptionHandler', exceptionHandlerDecorator)
    }

    angular.module('utils')
        .config(['$provide', utilModuleConfiguration])
}());

I suggest using the $exceptionHandler in your code as well. It provides a central service that catches and handles errors in the app, whether it’s an angular exception, or our own.

AngularJS   Tips
Earlier Ctrl + ↓