Remix.run集成Nivo Charts编译失败:ESM模块导入错误求助
Remix.run 搭配 Nivo Charts 编译失败问题排查
报错信息
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\tomer\Code\remix-es\node_modules\d3-color\src\index.js from C:\Users\tomer\Code\remix-es\node_modules\@nivo\colors\dist\nivo-colors.cjs.js not supported. Instead change the require of index.js in C:\Users\tomer\Code\remix-es\node_modules\@nivo\colors\dist\nivo-colors.cjs.js to a dynamic import() which is available in all CommonJS modules.
当前配置
已尝试将相关包加入serverDependenciesToBundle,remix.config.js片段如下:
module.exports = { tailwind: true, ignoredRouteFiles: ["**/.*"], serverDependenciesToBundle: ["d3-color", "d3", "@nivo"], };
问题原因
@nivo和d3都是包含多个子包的命名空间集合,直接写入根包名(@nivo、d3)无法让Remix识别并打包所有嵌套的ES模块子包。比如报错中涉及的@nivo/colors就属于@nivo的子包,未被正确匹配到,导致服务端运行时尝试用CommonJS加载纯ESM的d3-color模块,触发错误。
解决方法
修改serverDependenciesToBundle配置,用正则匹配所有相关子包,或者明确列出用到的具体子包:
方案1:正则匹配所有子包
module.exports = { tailwind: true, ignoredRouteFiles: ["**/.*"], serverDependenciesToBundle: [ /^d3-.*/, // 匹配所有d3开头的子包 /^@nivo\/.*/ // 匹配所有@nivo下的子包 ], };
方案2:明确列出用到的子包
如果仅使用部分Nivo组件,可直接列出具体子包,减少打包体积:
module.exports = { tailwind: true, ignoredRouteFiles: ["**/.*"], serverDependenciesToBundle: [ "d3-color", "d3-scale", // 根据实际用到的d3子包添加 "@nivo/colors", "@nivo/bar" // 根据实际用到的Nivo组件添加 ], };
内容的提问来源于stack exchange,提问作者momi
相关产品推荐
相关产品推荐

