升级Next.js 13后NX Monorepo项目Webpack构建失败求助
使用NX管理Monorepo项目,升级Next.js到13版本后,应用无法完成构建,Webpack处理import/export及TypeScript相关代码时频繁报错。开发环境运行正常,但构建时出现大量类似如下的错误:
../../libs/queries/src/lib/groq/searchFaq.ts Module parse failed: Unexpected token (1:37) 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 const searchFaqQuery = (market: string, language: string, searchTerm: string) => { | const searchTermArray = searchTerm.split(' ').map((word) => word + '*'); | const queryFilters = `market == '${market}' && language == '${language}' && _type == 'faq' && !(_id in path("drafts.**"))`; Import trace for requested module: ../../libs/queries/src/lib/groq/searchFaq.ts ../../libs/queries/src/index.ts ../../libs/utils/src/lib/components/atoms/BulletListWrapper/BulletListWrapper.tsx Module parse failed: Unexpected token (4:5) 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 | import * as Styled from './BulletListWrapper.style'; | > type TBulletListWrapper = { | children: React.ReactNode; | }; Import trace for requested module: ../../libs/utils/src/lib/components/atoms/BulletListWrapper/BulletListWrapper.tsx ../../libs/utils/src/lib/components/atoms/index.ts ../../libs/utils/src/lib/components/index.ts ../../libs/utils/src/index.ts
当前项目的next.config.js配置如下:
module.exports = { env: { NEXT_PUBLIC_TOKEN: process.env.NEXT_PUBLIC_SANITY_TOKEN, NEXT_PUBLIC_PREVIEW_SECRET: process.env.NEXT_PUBLIC_SANITY_PREVIEW_SECRET, NEXT_PUBLIC_PROJECT_ID: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, }, i18n: { defaultLocale: 'et', locales: ['et', 'ru'], }, basePath: '/ee', reactStrictMode: true, images: { domains: ['cdn.images.io'], formats: ['image/webp'], }, experimental: { forceSwcTransforms: true, }, swcMinify: true, webpack(config) { config.resolve.fallback = { fs: false, path: false }; config.module.rules.push({ test: /\.svg$/, issuer: { and: [/\.(js|ts)x?$/], }, use: ['@svgr/webpack'], }); return config; }, };
配置Next.js转译Monorepo库:Next.js 13默认不会处理Monorepo中
libs目录下的外部包代码,需在next.config.js中添加transpilePackages配置,指定需要转译的libs包名(对应libs目录下package.json的name字段)。示例:module.exports = { // ...其他配置 transpilePackages: ['@your-project/queries', '@your-project/utils'], };这会让Next.js自动转译这些库的TS/TSX代码,解决loader缺失问题。
匹配NX与Next.js版本兼容性:确认当前NX版本支持Next.js 13,若版本不兼容,运行
nx update升级NX及相关插件,确保依赖版本匹配。排查SWC与Babel冲突:当前配置开启了
experimental.forceSwcTransforms和swcMinify,如果Monorepo的libs仍使用Babel编译,可能引发冲突。可尝试暂时关闭forceSwcTransforms,或统一将libs配置为使用SWC编译。检查libs的TypeScript配置:确认libs目录下的
tsconfig.json中,compilerOptions.target、module等配置与Next.js 13要求兼容,避免语法不兼容导致构建失败。同时确保libs的构建输出目录正确,生成可被Next.js识别的代码。验证webpack规则完整性:虽然Next.js默认处理TS/TSX文件,但需确保webpack配置未覆盖默认规则。若自定义了webpack规则,检查是否遗漏对Monorepo libs文件的处理逻辑。
内容的提问来源于stack exchange,提问作者seven

