nx.dev monorepo中next.config.js导入库遇Unexpected token 'export'错误咨询
解决NX Monorepo中Next.js配置文件导入内部库的语法错误
问题描述
在NX.dev Monorepo中创建空Next.js模板和默认JS库后,执行nx dev project-app时报错:处理项目图失败,具体错误为apps/project-app/next.config.js存在Unexpected token 'export'。
相关代码:
apps/project-app/next.config.js
//@ts-check // eslint-disable-next-line @typescript-eslint/no-var-requires const { composePlugins, withNx } = require('@nx/next'); const {mylib} = require('@project/mylib'); console.log(mylib()) /** * @type {import('@nx/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { nx: { svgr: false, }, }; const plugins = [ withNx, ]; module.exports = composePlugins(...plugins)(nextConfig);
mylib/src/index.ts
export function mylib(): string { return 'mylib'; }
错误原因
next.config.js默认是CommonJS模块(使用module.exports),而你的mylib默认编译输出的是ES模块(包含export语句),Node.js的require无法直接加载ES模块,因此触发语法错误。
解决方案
方法1:修改mylib编译配置,输出CommonJS格式
在mylib的project.json中调整build目标的输出格式:
{ "targets": { "build": { "executor": "@nx/js:tsc", "options": { "outputPath": "dist/mylib", "main": "mylib/src/index.ts", "tsConfig": "mylib/tsconfig.lib.json", "format": ["cjs"] } } } }
修改后重新构建库:nx build mylib,再运行nx dev project-app即可正常导入。
方法2:将next.config.js改为ES模块
把next.config.js重命名为next.config.mjs,并切换为ES模块语法:
//@ts-check import { composePlugins, withNx } from '@nx/next'; import { mylib } from '@project/mylib'; console.log(mylib()); /** * @type {import('@nx/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { nx: { svgr: false, }, }; const plugins = [ withNx, ]; export default composePlugins(...plugins)(nextConfig);
NX会自动识别.mjs后缀的配置文件,无需额外调整。
方法3:在next.config.js中使用动态导入
如果不想修改库或配置文件格式,可利用Next.js支持异步配置函数的特性,动态导入ES模块:
//@ts-check const { composePlugins, withNx } = require('@nx/next'); /** * @type {import('@nx/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { nx: { svgr: false, }, }; const plugins = [ withNx, ]; module.exports = async () => { const { mylib } = await import('@project/mylib'); console.log(mylib()); return composePlugins(...plugins)(nextConfig); };
内容的提问来源于stack exchange,提问作者Egor Mamoshin
相关产品推荐
相关产品推荐

