Prevent Duplicating Typescript Path Configurations in Monorepo

669 Views Asked by At

Gist

I like to follow the "dry" (don't repeat yourself) principle. But currently I have nearly the same path configuration in three different places:

1. Typescript config file

I have a monorepo with multiple Bazel Typescript packages, and thus I need to reference them with paths like this inside tsconfig.json

"paths": {
  "@cents-ideas/enums": ["./packages/enums"],
  "@cents-ideas/utils": ["./packages/utils"],
  "@cents-ideas/event-sourcing": ["./packages/event-sourcing"],
  "@cents-ideas/models": ["./packages/models"]
},

2. Node package file

For development with ts-node I also need to add the paths to the package.json so that Node.Js can recognize the Typescript aliases. (I am using a package called module-alias for this.

"_moduleAliases": {
  "@cents-ideas/enums": "./packages/enums",
  "@cents-ideas/utils": "./packages/utils",
  "@cents-ideas/event-sourcing": "./packages/event-sourcing",
  "@cents-ideas/models": "./packages/models"
}

3. Jest config file

Finally I also need to add those paths to my Jest config, so that the tests can find the paths:

moduleNameMapper: {
  '^@cents-ideas/utils(.*)$': '<rootDir>/packages/utils$1',
  '^@cents-ideas/event-sourcing(.*)$': '<rootDir>/packages/event-sourcing$1',
  '^@cents-ideas/enums(.*)$': '<rootDir>/packages/enums$1',
  '^@cents-ideas/models(.*)$': '<rootDir>/packages/models$1',
},

Goal

My goal is to have one common place where I can put the paths and all other places will be updated automatically.


Just in case you need further insight into the project, you can check it out here: https://github.com/flolude/cents-ideas

2

There are 2 best solutions below

0
On BEST ANSWER

Typescript config file

"paths": {
  "@cents-ideas/*": ["./packages/*"]
},

Node package file

const moduleAlias = require('module-alias');

const registerAliases = () => {
  if (process.env.ENV === 'dev') {
    const fs = require('fs');
    const paths: string[] = fs.readdirSync('./packages');
    paths.forEach(addPackageAlias);
  }
};

const addPackageAlias = (name: string) => {
  moduleAlias.addAlias(`@cents-ideas/${name}`, `${__dirname}../../../packages/${name}`);
};

registerAliases();

Jest config file

Fixed with the help of Bazel. But I am sure that Jest supports similar wildcards as the Typescript config.

1
On

You're using yarn, so probably you should take a look into yarn workspaces. You should be able to add

package.json
{
  //...
  "workspaces": [
    "packages/*
  ]
}

And run yarn which will make symlinks into node_modules and you should be able to remove all of the three configurations above