首页 > 解决方案 > 如何通过 Yarn Workspaces 在 NestJS 中进行代码共享

问题描述

我正在尝试为一个简单的 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)

(这是导致 API 崩溃的受影响代码行)

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

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

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

标签: typescriptnext.jsnestjsmonorepoyarn-workspaces

解决方案


From a brief look, it's how the shared library gets compiled that's the problem. ESM vs CJS, essentially. ES Modules use the exports syntax (front end libraries especially), but Node still uses CommonJS with module.exports so it sees exports and throws an error


推荐阅读