Adding aliases with Babel

Had enough of complicated import and require statements in your Node/JavaScript files? I’m used to developing in Vue which uses Webpack aliases that by default sets up the @ alias that points to the src directory. I’m working on a project that I am using Babel but not Webpack. It turns out Babel has the cool plugin babel-plugin-module-resolver that also setup aliases.

Install the plugin.

$ npm i --save-dev babel-plugin-module-resolver

So we have the following directory structure.

├── src
│  └─ MyCoolService
│    └─index.js
│  └── index.js
├── test
│  └── MyCoolService.spec.js
│  .babelrc
│  package.json

In the spec file I want to test MyCoolService. Importing is messy.

import MyCoolService from '../src/MyCoolService'

I want to do it the Vue way.

import MyCoolService from '@/MyCoolService'

Can it be done? O yes, babel-plugin-module-resolver to the rescue! Create a .babelrc file with the following contents.

// .babelrc
  "plugins": [
    ["module-resolver", {
      "root": ["./src/**"]
      "aliases": [
        "@": "./src"

Now we can import with the @ alias. Alternatively as the root points to src you can also import as follows.

import MyCoolService from 'MyCoolService'

How cool is that? Happy coding!


Fix Jest describe/it/expected not recognised in Webstorm

Don’t you just hate it when Webstorm underlines functions as unknown, because it doesn’t recognise them? It turns out it is pretty simple to fix if you know how and have a TypeScript (ts) file with definitions available.

It turns out there is a much easier way of adding the definitions.

In File > Settings… > Languages & Frameworks > JavaScript > Libraries, click the button Download..., select ‘jest’ from the list of available definitions, click the button Download and Install. That’s it!

Webstorm rules!

First we need to install the Jest TypeScript definitions.

npm install --save-dev @types/jest

Then we need to add them in Webstorm by adding it as JavaScript library in the Settings.

File > Settings... >  Languages & Frameworks > JavaScript > Libraries

In the dialog click the Add.. button. The following dialog is opened.

Webstorm add JavaScript Library

In the dialog enter the following information.

Name: Jest
Visibility: Project

Then click on the + button and select the option Attach files....

Webstorm add JavaScript Library

The Jest TypeScript definitions are installed in the node_modules directory under your project directory. The Jest TypeScript definitions are installed in @types\jest\index.d.ts. Select the file and click the OK button.

That’s it! Now Webstorm recognises Jest describe/it/expect. O yeah!