You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS跨项目共享组件报错:无法导入外部组件及模块解析失败

Fixing Cross-Project Shared Component Parse Error in Next.js

Hey there, let's tackle that component sharing error you're seeing! That "Unexpected token" parse failure happens because your desktop and mobile Next.js projects aren't set up to transpile the shared SharedComponent.js—since it lives outside each project's root directory, Next.js doesn't process its JSX syntax by default. Here are the most reliable fixes, depending on your Next.js version:

Next.js 13 introduced transpilePackages specifically for this kind of cross-project/shared code scenario. It tells Next.js to treat external directories as part of your project and transpile their code.

Add this to both your desktop/next.config.js and mobile/next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['../components'],
}

module.exports = nextConfig

After updating the configs, restart your development servers—this step is crucial, as Next.js doesn't hot-reload config changes.

2. Custom Webpack Config (Next.js 12 or Earlier)

If you're stuck on an older Next.js version, you'll need to tweak the webpack setup to include your shared component directory in the babel transpilation process.

Add this to both project's next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config, { isServer }) => {
    // Tell webpack to transpile the shared component file
    config.module.rules.push({
      test: /\.(js|jsx)$/,
      include: [require.resolve('../components/SharedComponent.js')],
      use: ['babel-loader'],
    });
    return config;
  },
}

module.exports = nextConfig

Also, make sure your project has a valid Babel config (either .babelrc or babel.config.json in each project root) with the Next.js preset:

{
  "presets": ["next/babel"]
}

Quick Checks to Avoid Headaches

  • Double-check the path to your components directory in the config—typos here are a common culprit!
  • Ensure your shared component uses a valid extension: .js works, but if you're having issues, try renaming it to .jsx (Next.js handles both, but explicit extensions can resolve edge cases).
  • Always restart your dev server after changing config files—this is easy to forget but essential.

内容的提问来源于stack exchange,提问作者Cyril Sadasivan Panicker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:07:57