Tuesday, 1 October 2019

How to use yarn workspaces with typescript and out folders?

I'm trying to set up a monorepo using yarn. I'm confused as to how to set up typescript with project references such that things resolve properly.

For example, if I have a folder structure like

/cmd
/client

And I want cmd to depend on client I could have:

cmd/tsconfig.json:

{
  "compilerOptions": {
    "types": ["reflect-metadata", "jest"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": "node",
    "declaration": true,
    "importHelpers": true,
    "composite": true,
    "target": "esnext"
    "sourceRoot": "src",
    "outDir": "dist"
  },
  "references": [
    {
      "path": "../client"
    }
  ],
  "include": [
    "src/**/*"
  ]
}

with a package.json

{
  "name": "cmd",
  "version": "1.0.0",
  "dependencies": {
    "client": "^1.0.0",
  }
}

In this model both cmd and client get compiled with an outDir and sourceRoot field set in their tsconfig. This means all their compiled javascript goes into the dist/ subfolder of cmd/dist and client/dist

If now I try and reference a class from client into cmd like

import Foo from 'client/src/foo'

The IDE is perfectly happy to resolve this since it seems that its mapped via the typescript references property.

However, the compiled javascript boils down to a

const foo_1 = require("client/src/foo");

However, the actual built javascript is in client/dist/src/foo, so at runtime this never works.

On the flip side, if I don't use sourceRoots and outDirs and have the javascript inlined with the typescript files at the same folder everything does work (but makes the repo dirty and requires custom gitignores to exclude things)

Can anyone shed any light on how to properly set up a typescript 3.x monorepo with yarn workspaces such that things just work?



from How to use yarn workspaces with typescript and out folders?

No comments:

Post a Comment