【发布时间】:2020-01-31 20:19:20
【问题描述】:
我在一个单一存储库中有 2 个 CRA 项目 - P1 和 P2。
root/
projects/
p1/
package.json
tsconfig.json
src/
shared/
**/*.ts
p2/
package.json
tsconfig.json
src/
**/*.ts
P1 包含一些共享基础架构源文件,我想在P2 中重复使用。
注意:我知道这种方法的缺点和负面影响,但是......
我尝试了什么:
-
从
P2中包含P1并导入:-
P1 tsconfig.json修改为"include": [..., "root/projects/p1/src/shared/**/*.ts] -
P2源文件通过相对路径导入.ts文件
结果:
You attempted to import <path> which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/ -
-
使用纱线工作区
这个很简单。 Yarn does not allow 在项目根目录之外拥有工作区
You cannot and must not reference a workspace that is located outside of this filesystem hierarchy. -
Typescript 3.0+ 项目参考:
- 将
p1 tsconfig.json更新为
"compilerOptions": { "composite": true }- 添加对
P1 tsconfig.json的引用
references: [ { "path": "{...}/p1/" ]使用
tsc -b构建P1以生成声明文件-
现在我需要以某种方式导入它。
创建
tsconfig.paths.json到configurepaths部分添加
rootDirtpP1 tsconfig.json以指向root/文件夹添加路径
"@lib/*": ["<relative-path-to-p1>/p1/src/shared/*"]
结果:
Cannot find module: '@lib/....'. Make sure this package is installed我还看到 VSCode 可以正确识别我的配置并且
importintellisense 可以正常工作 - 将
-
使用
react-app-rewired在我的
config-overrides.js我添加了类似的东西module.exports = function override(config, env) { config.resolve.alias = { "@lib": path.resolve(__dirname, '...p1/src/shared/') } }这适用于项目中的所有别名。但就我而言,它失败了
You attempted to import <root>/p1/src/shared... which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/
【问题讨论】:
标签: typescript create-react-app yarnpkg