Skip to content

Instantly share code, notes, and snippets.

@chalsy87
Created December 14, 2018 07:09
Show Gist options
  • Save chalsy87/e9e3fee87f0ba61a2fe677ed71705a72 to your computer and use it in GitHub Desktop.
Save chalsy87/e9e3fee87f0ba61a2fe677ed71705a72 to your computer and use it in GitHub Desktop.
Use of alias in VSCode with Jest in a typeScript/JavaScript project

webPack-VSCode-Jest-alias-configuration

This are the necessary steps about How to configure alias in WebPack, VSCode and Jest.

Problem: We want to avoid the type of imports where you have to 'calculate' the path, intead of that we want to use a more friendly alias.

import { thing } from "../../../src/common/util"

​   |--> import { thing } from "commonpath/util"

import 'thing-to-test' from '../../../../../src/feature/subfeature/helper/thing

​   |--> import 'thing-to-test' from 'helperpath/thing

Now to solve this let's put this structure as a simple example:

    src

    ​ |--> api / file1

    ​ |--> commonApp / file2

in this case to import file 2 into file 1 we have to 'calculate' the path like "../commonApp/file2"

To do that we have to configure the 3 of them:

Webpack

Use the property resolve.alias in your config. file (no extra plugins are needed).

So in the webpack.commons.js or webpack.config.js let's type:

module.exports = {

​  resolve: {

    alias: {

      api: path.resolve(__dirname, './src/api/'),

      commonApp: path.resolve(__dirname, './src/common-app/')

},

extensions: ['.js', '.jsx', '.ts', '.tsx'],

mainFields: ['browser', 'module', 'main'],

},

Note: This is not enought for VSCode, it's Intellisense still will mark this kind of imports as errors.

VSCode

Making VSCode ‘smarter’, means allowing Intellisense to undertand those type of import when were are typing

In tsconfig.json (typescript projects) or jsconfig.json (javascript projects) we will add our paths.

{

  "compilerOptions": {

        "target": "es6",

        "module": "es6",

        "baseUrl": "./src/",

        "paths": {

              "api": ["./src/api/*"],

​               "commonApp": ["./src/common-app/*"]

​         }

},

  "exclude": [

        "node_modules"

  ]

}

Jest

Finally for Jest, we will configure package.json file using the moduleNameMapper property. Or you may have jest configuration exported to another file like : config/test/jest.json

Jest will use regular expressions to understand what an alias really means.

"moduleNameMapper": {

   "^api/(.)$": "/src/api/$1",

   "^commonApp/(.)$": "/src/common-app/$1"

}

NOTE: normally you will find that people use as part of the regular expression but in the end is how you wanna build it.

NOTE: parent routes "/src" must be after children roots "/src/components"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment