Emanuel
Emanuel

Reputation: 3267

Monorepo avoid (Cannot find module 'lib') when import a class from other project file

I'm using types/interfaces/classes from /backend folder inside /frontend folder in my simple monorepo, but my frontend dont have some backend libs There is a way to import class defined in files that use some libs without error Cannot find module 'libname', without creating a third file or shared folder that dont import any lib?

Current folder structure example

/root

  /backend
    /models/alternative.model.ts

  /frontend
    /components/frontend.component.ts

Example backend file alternative.model.ts

import { ObjectType } from '@nestjs/graphql';
import { BaseModel } from '../../common/models/base.model';
import { Exercise } from '../exercise/exercise.model';

@ObjectType()
export class Alternative extends BaseModel {
  text: string;
  isAnswer: boolean;
  exerciseId: string;
  exercise: Exercise;
}

Example frontend import frontend.component.ts

import { Alternative } from '../../../../../../backend/src/cases/alternative/alternative.model'

Example import error at build

../backend/src/cases/alternative/alternative.model.ts:1:46
Type error: Cannot find module '@nestjs/graphql' or its corresponding type declarations.

share class file cross projects monorepo

Upvotes: 0

Views: 889

Answers (1)

Emanuel
Emanuel

Reputation: 3267

My workaround was install all dependencies at backend before trying to build frontend

I was using docker, and this is my example dockerfile (nextjs frontend)

FROM node:lts-alpine AS deps
WORKDIR /app
COPY . .
WORKDIR ./backend
RUN npm install
WORKDIR ../frontend
RUN yarn install --frozen-lockfile

FROM node:lts-alpine AS builder
ENV NODE_ENV=production
WORKDIR /app
COPY . .
WORKDIR ./backend
COPY --from=deps /app/backend/node_modules ./node_modules
WORKDIR ../frontend
COPY --from=deps /app/frontend/node_modules ./node_modules
RUN yarn build

FROM node:lts-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/frontend/next.config.js ./
# COPY --from=builder /app/frontend/public ./public
COPY --from=builder /app/frontend/.next ./.next
COPY --from=builder /app/frontend/node_modules ./node_modules
CMD ["node_modules/.bin/next", "start"]

Upvotes: 0

Related Questions