Import from barrel files TypeScript/Yarn v4 monorepo

51 views Asked by At

I'm working on a small monorepo project, using Yarn 4 workspaces with TypeScript. I've mostly got it working, but I've hit an edge(ish) case with some import paths.

I have a common library in this repo with the following package.json:

{
  "name": "@example/common",
  "exports": {
    "./*": {
      "default": "./lib/*.js",
      "types": "./lib/*.d.js"
    }
  },
}

This project builds its source code to the project's lib folder.

In my other projects, I've added "@example/common": "workspace:*" as a dependency. This allows me to import any named modules under common. For example, common contains src/utils.ts. This builds a matching lib/utils.js file (with corresponding type declarations), and I can import it like so:

import { doSomething } from '@example/common/utils'

This is great as I don't need any custom TS paths - it "just works" with the normal resolution algorithm and I get the correct imports during runtime, and the correct typings when editing/compiling.

However, with this setup, I'm not able to import from folders with barrel files (index.js) in them implicitly. If common contains src/utils/stuff.ts, and a src/utils/index.ts file that re-exports the stuff module's imports, I can't do this:

import { somethingFromStuff } from '@example/common/utils'

I have to explicitly import @example/common/utils/index, and then I might as well not have it.

Question

Is there any way to configure the export mappings so that I keep the existing working behavior (being able to import utils.ts by importing from @example/common/utils) while also being able to import stuff/index.ts by importing from @example/common/stuff (implicitly picking up the index file)? I'd prefer to avoid custom TS paths if possible.

I have both "module" and "moduleResolution" set to "node16" in my TS config if that's relevant.

0

There are 0 answers