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

Next.js集成Chart.js及Zoom插件时出现exports主定义缺失错误

问题:Next.js集成react-chartjs-2与chartjs-plugin-zoom时触发"exports main未定义"错误

我正在尝试用Next.js、react-chartjs-2和chartjs-plugin-zoom实现图表缩放功能,相关配置和代码如下:

package.json

{
  "dependencies": {
    "@auth0/nextjs-auth0": "^2.0.1",
    "@fortawesome/fontawesome-free": "^6.2.1",
    "@types/node": "18.11.13",
    "@types/react": "18.0.26",
    "@types/react-dom": "18.0.9",
    "chart.js": "^4.0.1",
    "chartjs-plugin-zoom": "^2.0.0",
    "classnames": "^2.3.2",
    "eslint": "8.29.0",
    "eslint-config-next": "13.0.6",
    "next": "13.0.6",
    "nextjs-progressbar": "0.0.16",
    "react": "18.2.0",
    "react-chartjs-2": "^5.0.1",
    "react-cookie-consent": "^8.0.1",
    "react-dom": "18.2.0",
    "typescript": "4.9.4"
  },
  "devDependencies": {
    "@types/chart.js": "^2.9.37",
    "autoprefixer": "^10.4.13",
    "moment": "^2.29.4",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext", "ES2015"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "helpers/index.js"],
  "exclude": ["node_modules"]
}

插件注册代码

import zoomPlugin from 'chartjs-plugin-zoom';

Chart.register(
  zoomPlugin
);

运行后触发错误:Error: No "exports" main defined in /app/node_modules/chart.js/package.json

我怀疑是tsconfig的编译选项有问题,但找不到具体原因。


解决方法

  1. 更新chart.js类型依赖
    你安装的@types/chart.js是2.x版本,但实际使用的chart.js是4.x,版本不匹配会导致模块解析异常。执行命令更新类型依赖:

    npm uninstall @types/chart.js
    npm install @types/chart.js --save-dev
    
  2. 调整tsconfig的模块解析策略
    chart.js 4.x使用了ES模块导出,将tsconfig.json中的moduleResolution改为bundler(Next.js 13+推荐):

    "moduleResolution": "bundler"
    
  3. 正确导入Chart实例
    确保从chart.js正确导入Chart对象,避免全局引用导致的解析问题:

    import { Chart } from 'chart.js';
    import zoomPlugin from 'chartjs-plugin-zoom';
    
    Chart.register(zoomPlugin);
    
  4. 兼容Next.js的ES模块解析
    如果使用Next.js 13的App Router,可在next.config.js中添加如下配置,确保ES模块正常解析:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      experimental: {
        esmExternals: 'loose',
      },
    };
    
    module.exports = nextConfig;
    

内容的提问来源于stack exchange,提问作者Tolga Yiğit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:01:36