使用 yarn workspaces 和 typescript 的 project references 来引用另一个 package 子目录

Use yarn workspaces and typescript's project references to reference another package subdirectory

我使用 yarn workspaces 并有以下包:

我希望能够从 x-core 子目录导入符号,就像您做的那样 import map from 'lodash/map',示例:

import { fn } from '@mycompany/x-core/test';

但我收到以下错误:

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.

如果它在库的根目录中导出,这仍然有效:

import { otherFn } from '@mycompany/x-core';

我在 Github 上做了一个小项目来准确展示我的设置,基于 lerna-yarn-workspaces-example: https://github.com/julienfouilhe/example-subdirectory-workspace-typescript-import

有没有办法做到这一点,我找不到任何有效的方法。我对模块解析了解不多,所以无法准确定位问题!

更新:使用 Nodejs 14,您可以在 package.json.

中指定子路径导出

https://nodejs.org/api/esm.html#esm_subpath_exports

我还没有亲自测试过,但看起来它可以通过使用

来解决这个问题
"exports": {
  ".": "./lib"
}

在构建时移动到根目录可以工作并避免工具问题,但如前所述,它会使构建复杂化,尤其是在工作区中共享时。 "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 . 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" 字段。如果您可以使用它,它似乎确实是 webpack 5 的一部分。因此,如果您不在单声道存储库之外发布您的库,那么无需使用更新的工具和一些配置工作将所有内容移至根目录即可解决此问题。