在Next.js(TypeScript)中使用第三方UI组件库时出现SyntaxError: Unexpected token 'export'错误的求助
Hey there, let's break down why this error is happening and how to fix it quickly:
What's Causing the Error?
Next.js runs part of its code in a Node.js environment (for server-side rendering/static site generation), which defaults to using CommonJS module syntax (require()/module.exports). But your @orgname/uikit is exporting code using ES Module syntax (export * from...), which Node.js can't parse directly without extra configuration.
Solutions to Fix This
1. Use Next.js Built-in transpilePackages (Next.js 13+ Recommended)
Next.js 13 added native support for transpiling external packages, which is the simplest fix:
- Open your
next.config.js(ornext.config.tsif you're using TypeScript for config) - Add the
transpilePackagesoption pointing to your UI kit:/** @type {import('next').NextConfig} */ const nextConfig = { transpilePackages: ['@orgname/uikit'], // Keep your existing config options here } module.exports = nextConfig - Restart your Next.js dev server. This tells Next.js to convert your UI kit's ES Module code into a format Node.js can handle.
2. For Next.js 12 or Earlier: Use next-transpile-modules
If you're on an older Next.js version, you'll need a third-party package:
- Install the package first:
npm install next-transpile-modules --save-dev # or yarn add next-transpile-modules --dev - Update your
next.config.js:const withTM = require('next-transpile-modules')(['@orgname/uikit']); module.exports = withTM({ // Your existing Next.js configuration goes here }); - Restart your dev server to apply the changes.
3. (If You Control the UI Kit) Fix the Package's Module Output
If you have access to modify the @orgname/uikit project, you can ensure it outputs both CommonJS and ES Module builds:
- In the UI kit's
package.json, add these fields (adjust paths to match your build output):{ "main": "./dist/cjs/index.js", // CommonJS entry "module": "./dist/esm/index.js", // ES Module entry "types": "./dist/types/index.d.ts" // TypeScript types }
This lets Next.js automatically pick the right module format for each environment.
Verify the Fix
After applying one of the above solutions, import your UI kit components in your Next.js pages again (e.g., import { Button } from '@orgname/uikit') and run your dev server. The error should be gone!
内容的提问来源于stack exchange,提问作者Rodrigo

