DEV Community

Arthur V. M. Dantas
Arthur V. M. Dantas

Posted on • Originally published at


Setting up absolute paths in Parcel and TypeScript


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

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";
Enter fullscreen mode Exit fullscreen mode

Using absolute path, importing the same module is simpler:

// I start from the "root" directory
import { Example } from "lib/lib";
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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



Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!