简体   繁体   English

如何在@nrwl/nx monorepo 中导入绝对路径?

[英]How to import absolute paths in a @nrwl/nx monorepo?

I'm working on a @nrwl/nx monorepo.我正在开发一个@nrwl/nx monorepo。 I want to import the folders inside the project src by the absolute paths.我想通过绝对路径导入项目src中的文件夹。 I tried specifying the baseUrl but didn't work.我尝试指定baseUrl但没有用。 The only solution worked is, adding the path to the monorepo root tsConfig.json file as follows.唯一可行的解决方案是,将路径添加到 monorepo 根tsConfig.json文件,如下所示。

"paths": {
   "*": ["apps/my-app/src/*"]
}

But, the problem is, if I have another project, I will have to add that project as well to this path.但是,问题是,如果我有另一个项目,我将不得不将该项目也添加到此路径中。 I tried something as follows.我尝试了以下方法。

"paths": {
   "*": ["apps/*/src/*"]
}

But, this doesn't work anymore.但是,这不再起作用了。 It doesn't match the project folder name.它与项目文件夹名称不匹配。

How can I solve this?我该如何解决这个问题? Or, is there any better way to import by absolute paths?或者,有没有更好的方法通过绝对路径导入?

I'm facing the same problem, due to organizing common DTOs and Event.ts files in the nx monorepo.由于在 nx monorepo 中组织了常见的 DTO 和 Event.ts 文件,我面临着同样的问题。 I found useful to update the tsconfig.base.json with a simpler path shortcut, that allow cross app imports and at the same time mantains the options of setting an absolute path in the single apps tsconfig.json file.我发现使用更简单的路径快捷方式更新 tsconfig.base.json 很有用,它允许跨应用程序导入,同时保留在单个应用程序 tsconfig.json 文件中设置绝对路径的选项。

Here's my base.json:这是我的基础。json:

"baseUrl": ".",
"paths": {
  "libs": [
    "libs/"
  ],
  "app1: [
    "apps/app1/"
  ],
  "app2": [
    "apps/app2/"
  ],
}

Now I have a sort of absolute imports that point to app names as base:现在我有一种以应用程序名称为基础的绝对导入:

import {CreateUserEvent} from 'libs/events/create-user.event';

This is a random file in the app1/src/app/ folder that import a file in libs folder这是 app1/src/app/ 文件夹中的一个随机文件,用于导入 libs 文件夹中的文件

Folder structure is:文件夹结构为:

root ('.') 
|__ app1/src/app/file_with_import.ts
|__ ... 
|__ ...
|__ libs/events/create_user.event.ts

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM