#3 - Setting up absolute paths in Parcel and TypeScript

Motivation

Absolute paths are very useful. Instead of importing modules using relative paths, first descending to the root level and then going up again, when we use absolute paths we just need the "going up" part because we start from the root directory already.

One of the main advantages of absolute paths over relative ones is the independence of file location within the project; that is, you can move the file to a new location without having to edit its contents.

As an example, let's imagine that we have the following directory structure:

An example of directory structure
Common directory names in a project folder 😁

Using relative path, to import something from lib.ts into fool.ts I would have to write:

// first I "go down" and then "go up" again
import { Example } from  "../../../lib/lib";

Using absolute path, importing the same module is simpler:

// I start from the "root" directory
import { Example } from "lib/lib";

The "problem" here is that absolute paths do not work in TypeScript or Parcel by default.

Absolute paths in TypeScript

To be able to use absolute paths in TypeScript we can set the baseUrl property in the tsconfig.json file. With this, we define src as our root directory (for module resolution).

// tsconfig.json
{
  ...
  "baseUrl": "./src"
  ...
}

According to TypeScript documentation(1):

Setting baseUrl informs the compiler where to find modules. All module imports with non-relative names are assumed to be relative to the baseUrl.

Absolute paths in Parcel

Although Parcel works very well with TypeScript, it does not use the baseUrl property of tsconfig.json to resolve module paths. For it to be able to find the files, there is a proper configuration - using aliases(2) - to be added to package.json

// package.json
{
  ...
  "alias": {
    "lib": "./src/lib"
  }
  ...
}

That's it! Now our code import { Example } from "lib/lib"; works as expected and modules paths are resolved accordingly. 🙂


English is not my main language, but I'm trying to improve on it. If you find any errors, please let me know: @arthurvmdantas.

  1. https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url
  2. https://parceljs.org/features/dependency-resolution/#aliases
  3. https://www.typescriptlang.org/tsconfig#baseUrl

Arthur V. M. Dantas

Arthur V. M. Dantas

Brazil