reactjsnext.jsmonorepozodturborepo

Module parse failed using Next.js in a turborepo setup


I am using a monorepo using Turborepo:

apps
|__ api
|__ cms
packages
|__ validation-schemas

The validation-schemas packages is where I am implement all the zod validation schemas to be used in the api and cms apps.

import { z } from 'zod';

const schema = z.object({
    name: z.string(),
});

type SchemaType = z.infer<typeof schema>;

export {
    schema,
};
export type {
    SchemaType,
};

// index.ts
import {
    SchemaType,
    schema,
} from './admin';

export {
    schema,
};
export type {
    SchemaType
};
{
    "name": "validation-schemas",
    "version": "0.0.1",
    "description": "",
    "main": "src/index.ts",
    "types": "src/index.ts",
    "license": "MIT",
    "devDependencies": {
        "typescript": "^4.5.2"
    },
    "dependencies": {
        "zod": "^3.21.4"
    }
}

When importing the schema in the api project, I am having no problem. However, importing the schema in the cms Next.js app result in the following error:

error - ../../packages/validation-schemas/src/index.ts
Module parse failed: Unexpected token (54: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
|     schema,
| };
> export type {
|     SchemaType,

Import trace for requested module:
../../packages/validation-schemas/src/index.ts

Here is the code used in the Next.js app:

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import {
    SchemaType,
    schema,
} from 'validation-schemas';

function Component(): JSX.Element {
    const {
        handleSubmit,
        register,
    } = useForm<SchemaType>({
        resolver: zodResolver(schema),
    });

    ...
}

export default Component;

How to make this work?


Solution

  • The issue was that Next.js wasn't transpiling the shared validation-schemas package. To fix this, I needed to tell Next.js explicitly to transpile that package.

    I did this by adding the transpilePackages option to my next.config.js file, like so:

    /** @type {import('next').NextConfig} */
    
    const nextConfig = {
        ...
        transpilePackages: ['validation-schemas'],  // Here's the crucial addition
    };
    
    module.exports = nextConfig;
    

    After adding the validation-schemas package to the transpilePackages list and restarting the Next.js server, the error was resolved!

    Hope this helps someone else facing the same issue.