Next.js使用Yarn Workspaces时类型注解出现Module parse failed错误
问题描述
从Vite+React迁移到Next.js+React后,运行next dev时出现模块解析错误,仅在导入通过Yarn Workspaces添加的本地@project-name/backend包时触发:
Module parse failed: Unexpected token (5:20) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
错误出现在Zod错误映射的类型定义代码:
const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
当前项目依赖版本:
{ "typescript": "^5.1.6", "next": "^14.0.3", "react": "^18.2.0", "react-dom": "^18.2.0" }
项目结构:
project-name | - backend | - frontend
frontend的package.json依赖包含:
"dependencies": { "@project-name/backend": "1.0.0", ... }
解决方案
Yarn Workspaces和Next.js本身没有兼容性问题,问题出在Next.js默认不会编译node_modules中的未编译源码,而工作区本地包会被链接到node_modules,如果backend包是未编译的TypeScript/ESNext代码,就会触发解析错误。以下是修复步骤:
1. 配置Next.js编译工作区包
在frontend目录下创建或修改next.config.js,添加transpilePackages选项,指定需要编译的工作区包:
/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['@project-name/backend'], } module.exports = nextConfig
这个配置会让Next.js的webpack编译指定的工作区包,处理其中的TypeScript语法和ESNext特性。
2. 确保backend包的配置正确
- 如果
backend是TypeScript项目,确保其tsconfig.json的编译选项符合Next.js的兼容性要求,例如:{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "node", "declaration": true, "outDir": "./dist" }, "include": ["src/**/*"] } - 在
backend的package.json中指定正确的入口字段,让Next.js能找到编译后的文件或源码:
如果你不想提前编译{ "name": "@project-name/backend", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "tsc" } }backend,可以移除main字段,让Next.js直接读取backend的源码文件(配合transpilePackages使用)。
3. 验证Yarn Workspaces配置
根目录的package.json需要正确声明工作区:
{ "private": true, "workspaces": [ "backend", "frontend" ] }
确保在根目录执行yarn install,让Yarn正确链接工作区包。
补充说明
Next.js默认只编译项目自身的源码和经过预编译的第三方npm包,而本地工作区包通常是未编译的源码状态,因此需要显式告诉Next.js要编译这些包。通过transpilePackages配置即可解决这类模块解析错误。
内容的提问来源于stack exchange,提问作者The Blind Hawk
相关产品推荐
相关产品推荐

