antvis / G2Plot

:dango: An interactive and responsive charting library based on G2.
https://g2plot.antv.antgroup.com
MIT License
2.55k stars 605 forks source link

🤔 [QUESTION] 在 NuxtJS 中使用,CJS 语法的不兼容问题 #3780

Open AnzhiZhang opened 4 months ago

AnzhiZhang commented 4 months ago

🐛 Question description [Please make everyone to understand it]

Nuxt 是一个 Vue SSR 框架,我在使用 G2Plot 时,遇到了以下错误:

require() of ES Module /home/projects/paripjqkq.github/node_modules/d3-interpolate/src/index.js from /home/projects/paripjqkq.github/node_modules/@antv/g-base/lib/animate/timeline.js not supported. Instead change the require of index.js in /home/projects/paripjqkq.github/node_modules/@antv/g-base/lib/animate/timeline.js to a dynamic import() which is available in all CommonJS modules.

timeline.js 的相关代码:

var util_1 = require("@antv/util");
var d3Timer = require("d3-timer");
var d3_interpolate_1 = require("d3-interpolate"); // 目前整体动画只需要数值和数组的差值计算
var register_1 = require("./register");
var PathUtil = require("../util/path");
var color_1 = require("../util/color");

根据 Nuxt 的说明(https://nuxt.com/docs/guide/concepts/esm),这种情况可能是由于在 ESM 模块中使用了 CJS 语法。


我查到了相关的几个 issue:antvis/G2Plot#1894, antvis/G6#4646

https://github.com/antvis/G6/issues/4646#issuecomment-1593999758 这个解决方案可以解决 d3-interpolate 库的问题,但是还会有新的问题,也是因为使用了 require

require() of ES Module /home/projects/paripjqkq.github/node_modules/lodash-es/lodash.js from /home/projects/paripjqkq.github/node_modules/@antv/path-util/lib/parse-path.js not supported. Instead change the require of lodash.js in /home/projects/paripjqkq.github/node_modules/@antv/path-util/lib/parse-path.js to a dynamic import() which is available in all CommonJS modules.

以前的相关修复:antvis/G2#3141


请问是否可以协助确认,是否是 g2 生态的库使用了 cjs 语法导致的问题,以及能否建议一定的解决方案?如果能解决 esm 模块中的 cjs 导入就好了。

💻 Link to minimal reproduction

https://stackblitz.com/edit/github-cibroa?file=app.vue

🏞 Expected result

可以正常引入 G2Plot 并使用。

🚑 Any additional [like screenshots]

AnzhiZhang commented 4 months ago

在 Nuxt 官方提供的指导下(https://nuxt.com/docs/guide/concepts/esm#transpiling-libraries),设置 transpile,暂时可以使用了

build: {
    transpile: [
        "@antv",
    ],
},

但是该文档还提到

If you encounter these errors, the issue is almost certainly with the upstream library. They need to fix their library to support being imported by Node.

方便的话还是烦请帮忙检查一下 CJS 的语法问题