I use yarn workspaces and have the following packages:
I want to be able to import symbols from x-core subdirectories, the same way you would do import map from 'lodash/map'
, example:
import { fn } from '@mycompany/x-core/test';
But I get the following error:
tsc -b packages/x-core packages/x-cli
packages/x-cli/src/main.ts:1:20 - error TS2307: Cannot find module '@mycompany/x-core/test'.
1 import { fn } from "@mycompany/x-core/test";
~~~~~~~~~~~~~~~~~~~~~~~~
error Command failed with exit code 1.
This works though, if it is exported in the root of the library:
import { otherFn } from '@mycompany/x-core';
I made a small project on Github to show exactly my setup, based on lerna-yarn-workspaces-example: https://github.com/julienfouilhe/example-subdirectory-workspace-typescript-import
Is there a way to do this, I can't find anything that works. I don't know much about module resolution so I can't pinpoint the problem exactly!
Moving to the root at builds works and avoids tooling issues but as mentioned it complicates building, especially for sharing in workspaces. The "exports" field node 14 is an important change that should ultimately make supporting subdirectory exports easier but for now it only solves part of the problem since other tooling doesn't seem to respect the field yet. The specific error mentioned would still exist with typescript's path resolution that can be resolved using the "baseUrl"
and "paths"
options in your tsconfig.json
file at the root and then using "extends"
to share that config. Unfortunately if the lib ends up getting used by something built with webpack and you're using v4 you'll need to configure custom path resolution step because webpack doesn't support the "exports" field. It does appear to be part of webpack 5 if you can use that. So, if you're not publishing your lib outside of the mono repo then this is solvable without moving everything to the root with newer tools and some configuration work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With