I want to leverage monorepo by reusing types, DTOs, and other isomorphic app stuff from the backend (Nest.js) services within the same mono repo. In my case the next.js app and the nest.js app (which is a nest.js monorepo on its own) are on the same level in the root dir. I'm re-exporting a bunch of files in the nest-app/libs/types/src/index.ts
and then import it in my next.js app. But when I do so, next.js complains with Failed to compile error
The easiest way to reproduce the error is to do the following
- create an arbitrary folder for the monorepo, like
test-import
- navigate to the monorepo folder (
cd test-import
) - run
npx create-next-app@latest --typescript
and choose a name for the project (likenext-app
) - create the below
external.ts
file in the root of the monorepo (on the same level as thenext-app
) - run
npm run dev
from thenext-app
folder
Monorepo structure:
external.ts
next-app
(other files omitted)
pages
index.tsx
external.ts
export type ExternalType = string;
export const me = "ME";
next-app/pages/index.tsx
is importing content of external.ts
import { me } from "../../external";
// boilerplate code omitted
<h1 className={styles.title}>
Welcome {me} to <a href="https://nextjs.org">Next.js!</a>
</h1>
The following error is thrown:
../external.ts
Module parse failed: Unexpected token (1:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export type ExternalType = string;
|
| export const me = "ME";
CodePudding user response:
You need to use the experimental externalDir
feature: https://github.com/vercel/next.js/pull/22867.
// next.config.js
const nextConfig = {
...
experimental: {
externalDir: true
}
}
I have checked that it works at least in the case you have described.
This said, we also have a Nest Next monorepo — although in our case the shared code is outside of both Next and Nest — and to get it working we had to resort to symlinking (ln -s
) the shared code into the Nest folder. If you ever decide to have a folder with shared code that exists outside both the Next and Nest codebases, you might want to try this as well.
IIRC there is a way to get it working without a symlink but for that Nest has to manage the whole monorepo, including non-Nest subprojects.