在 monorepo 中导入 Next.js 应用程序中的共享代码

DK3*_*K3Z 11 typescript monorepo next.js

我想通过在同一 mono 存储库中重用来自后端 (Nest.js) 服务的类型、DTO 和其他同构应用程序内容来利用 monorepo。在我的例子中,next.js 应用程序和nest.js 应用程序(它本身就是一个nest.js monorepo)位于根目录中的同一级别。我正在重新导出一堆文件nest-app/libs/types/src/index.ts,然后将其导入到我的 next.js 应用程序中。但是当我这样做时,next.js 抱怨无法编译错误

重现错误的最简单方法是执行以下操作

  • 为 monorepo 创建任意文件夹,例如test-import
  • 导航至 monorepo 文件夹 ( cd test-import)
  • 运行npx create-next-app@latest --typescript并为项目选择一个名称(例如next-app
  • 在 monorepo 的根目录中创建以下external.ts文件(与 位于同一级别next-app
  • npm run devnext-app文件夹运行

Monorepo结构:

external.ts
next-app
  (other files omitted)
  pages
    index.tsx
Run Code Online (Sandbox Code Playgroud)

外部.ts

export type ExternalType = string;

export const me = "ME";

Run Code Online (Sandbox Code Playgroud)

next-app/pages/index.tsx正在导入内容external.ts

import { me } from "../../external";

// boilerplate code omitted
<h1 className={styles.title}>
  Welcome {me} to <a href="https://nextjs.org">Next.js!</a>
</h1>
Run Code Online (Sandbox Code Playgroud)

抛出以下错误:

../external.ts
Module parse failed: Unexpected token (1:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export type ExternalType = string;
| 
| export const me = "ME";
Run Code Online (Sandbox Code Playgroud)

Art*_*yom 10

您需要使用实验性externalDir功能:https://github.com/vercel/next.js/pull/22867

\n
// next.config.js\nconst nextConfig = {\n  ...\n  experimental: {\n    externalDir: true\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我已经检查过它至少在您描述的情况下有效。

\n
\n

这就是说,我们还有一个 Nest+Next monorepo \xe2\x80\x94,尽管在我们的例子中,共享代码位于 Next 和 Nest \xe2\x80\x94 之外,并且为了使其正常工作,我们必须求助于符号链接 ( ln -s)将共享代码放入 Nest 文件夹中。如果您决定拥有一个包含 Next 和 Nest 代码库之外的共享代码的文件夹,您可能也想尝试一下。

\n

IIRC 有一种方法可以让它在没有符号链接的情况下工作,但为此 Nest 必须管理整个 monorepo,包括非 Nest 子项目。

\n