6

I'm running into errors when I try to run the build artifact of a NestJS app that was created within an Nx workspace. The error only occurs when I run the resulting artifact anywhere outside of the repository where no node_modules folder exists.

Steps to reproduce:

  1. Clone this repo https://github.com/baumgarb/proxy-example
  2. Run npm install to install all packages
  3. Run ng build backend
  4. Go into the dist folder in dist/apps/backend
  5. Run node main.js in that folder, you should see the backend starting up successfully
  6. Now copy main.js to a different location outside of the cloned repository (e.g. /tmp or c:\temp)
  7. Run node main.js again in the new location and you'll run into the following error:

internal/modules/cjs/loader.js:775
    throw err;
    ^

Error: Cannot find module 'tslib'
Require stack:
- /home/bernhard/main.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
    at Function.Module._lo[ad (internal/modules/cjs/loader.js:677:27)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    ...[omitted for brevity] {
  code: 'MODULE_NOT_FOUND',
}

You can also try to run the build artifact in a Docker container, it will lead to the same error.

Here's also the comparison between my local machine and WSL: enter image description here

Can anyone tell me what the issue is and how to fix it? Thanks a lot in advance!

baumgarb
  • 1,955
  • 3
  • 19
  • 30

1 Answers1

0

I was having this problem when building a Docker image for a Nestjs app in a Nx workspace.

I did the following workaround:

# BUILD

FROM node:16.11.1-slim as build

WORKDIR /app/nx

COPY nx /app/nx

RUN npm install -g nx@13.1.3 && \
    npm install && \
    nx build backend


# SERVE

FROM node:16.11.1-slim

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /app/backend

COPY --from=build /app/nx/dist/apps/backend /app/backend

RUN npm install \
    tslib@2.3.1 \
    @nestjs/common@7.6.18 \
    @nestjs/core@7.6.18 \
    @nestjs/platform-express@7.6.18 \
    @nestjs/axios@0.0.3

EXPOSE 3333
CMD ["node", "/app/backend/main"]

doublethink13
  • 633
  • 8
  • 19