在 commonjs npm 模块中使用 d3

lin*_*ink 8 javascript commonjs d3.js esmodules

我正在创建一个私有 npm 包来可视化 Vuejs 项目的结构。d3 似乎是可视化的最佳选择之一,但我在将其包含在脚本中时遇到问题。在我在属性package.json下定义了我的脚本并导入了 d3 (正如我所看到的其他项目也这样做了)bin"bin": { "visualize": "vis.js" },

#!/usr/bin/env node

var path = require('path');
var fs = require('fs');
var d3 = require('d3');`. 
Run Code Online (Sandbox Code Playgroud)

但后来我收到以下错误

internal/modules/cjs/loader.js:1153
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: <Project Path>\node_modules\d3\src\index.js
require() of ES modules is not supported.`
Run Code Online (Sandbox Code Playgroud)

所以我将其更改为var d3 = import('d3');有效,但随后声明var d3tree = d3.tree()提出TypeError: d3.tree is not a function

是否可以在 commonjs 中使用 d3 ?或者也许还有另一个可以直接工作的图形可视化库。

fro*_*tto 1

import('d3') 动态加载d3您应该等待准备就绪的内容。

import('d3').then(d3 => {
     // use d3 here
});
Run Code Online (Sandbox Code Playgroud)

另一种选择是将项目从 commonjs 迁移到 ESM。