8

I am creating a private npm package to visualize the structure of a Vuejs project. d3 seems to be on of the best choices for a visualization, but I have problems to include it in my script. In the package.json I defined my script under the bin property "bin": { "visualize": "vis.js" }, and imported d3 (as I have seen other projects also did it this way)

#!/usr/bin/env node

var path = require('path');
var fs = require('fs');
var d3 = require('d3');`. 

But then I get the following error

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.`

So I changed it to var d3 = import('d3'); it works, but then the statement var d3tree = d3.tree() raises TypeError: d3.tree is not a function

Is it even possible to use d3 in commonjs? Or maybe there is another graph visualization library which works directly.

frogatto
  • 28,539
  • 11
  • 83
  • 129
link
  • 491
  • 1
  • 4
  • 13

1 Answers1

0

import('d3') dynamically loads d3 which you should wait for to be ready.

import('d3').then(d3 => {
     // use d3 here
});

Another choice is to migrate your project from commonjs to ESM.

frogatto
  • 28,539
  • 11
  • 83
  • 129