在turborepo设置中使用Next.js解析模块失败

lhcgjxsq  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(91)

我正在使用一个使用Turborepo的monorepo:

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

字符集
在validation-schemas包中,我实现了所有要在apicms应用程序中使用的zod验证模式。

import { z } from 'zod';

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

type SchemaType = z.infer<typeof schema>;

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

x

// 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"
    }
}

的字符串
api项目中导入模式时,我没有遇到任何问题。但是,在cms Next.js应用程序中导入架构会导致以下错误:

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


下面是Next.js应用程序中使用的代码:

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;


如何让这一切顺利进行呢?

8qgya5xd

8qgya5xd1#

问题是Next.js没有转译共享的validation-schemas包。为了解决这个问题,我需要显式地告诉Next.js来编译这个包。
我通过将transpilePackages选项添加到next.config.js文件中来做到这一点,如下所示:

/** @type {import('next').NextConfig} */

const nextConfig = {
    ...
    transpilePackages: ['validation-schemas'],  // Here's the crucial addition
};

module.exports = nextConfig;

字符集
在将validation-schemas包添加到transpilePackages列表并重新启动Next.js服务器后,错误得到解决!
希望这能帮助其他面临同样问题的人。

相关问题