【问题标题】:How to do code sharing in NestJS through Yarn Workspaces如何通过 Yarn Workspaces 在 NestJS 中进行代码共享
【发布时间】:2020-09-11 19:39:49
【问题描述】:

我正在尝试对一个简单的 monorepo 应用程序进行概念验证。我决定只使用Yarn Workspaces(我认为Lerna 可能有点矫枉过正)来设置我的包架构。

我有一个shared 包,用于与前端和后端共享代码。我成功地使它适用于前端(因为我在前端使用 NextJS 已经有一个名为 next-transpile-module 的 NPM 库来让一切顺利运行)但是现在,我被困在后端,而且我不确定这是否可能,因为我在 Google 上找不到信息。

这是我尝试启动 API 时抛出的错误:

/Users/Alfonso/git/taurus/packages/shared/dist/index.js:1
export var PRODUCT_NAME = "ACME";
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:1054:16)
    at Module._compile (internal/modules/cjs/loader.js:1102:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/Users/Alfonso/git/taurus/packages/api/dist/app.service.js:11:18)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)

(Here's the affected code line that makes the API blow up).

它在 GitHub 上,因此您可以克隆或查看 src 代码:https://github.com/alfonmga/taurus

您需要在根目录运行 yarn install 以安装项目依赖项,然后您还可以在根目录运行 yarn dev:client 以启动应用程序,yarn dev:api 以启动 API,yarn build:shared 以启动应用程序编译代码共享包(如果你愿意的话)。

P.S 这与我在 client 包中遇到的错误完全相同 (Unexpected token 'export'),但正如我所提到的,名为 next-transpile-module 的 NPM 库修复了它.. 所以它应该与转译有关,但是我不知道! :)

【问题讨论】:

    标签: typescript next.js nestjs monorepo yarn-workspaces


    【解决方案1】:

    简而言之,问题在于如何编译共享库。本质上,ESM 与 CJS。 ES 模块使用 exports 语法(尤其是前端库),但 Node 仍然使用带有 module.exports 的 CommonJS,因此它会看到 exports 并抛出错误

    【讨论】:

    • 解决办法是什么?
    猜你喜欢
    • 2018-08-27
    • 2021-02-22
    • 2018-11-07
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多