Search code examples
typescriptnext.jsnestjsmonorepoyarn-workspaces

How to do code sharing in NestJS through Yarn Workspaces


I'm trying to do a proof of concept for a simple monorepo application. I decided to just use Yarn Workspaces (I think Lerna maybe here is overkill) to set up my package architecture.

I have a shared package that I'm using to share code with the frontend and the backend. I successfully achieved to make it works for the frontend (As I'm using NextJS in the frontend there was already a NPM library named next-transpile-module to get everything running up smoothly) but now, I'm stuck at the backend, and I'm not sure if it's even possible because I couldn't find information on Google.

Here's the error that it's throwing up when I try to start the 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)

It's exactly the same error (Unexpected token 'export') that I was getting in the client package, but as I mentioned, that NPM lib named next-transpile-module fixed it.. so it should be something related to transpilation but I have no idea! :)


Solution

  • 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