Use d3 in an commonjs npm module
Asked Answered
D

1

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.

Dolce answered 8/7, 2021 at 8:51 Comment(0)
P
1

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.

Paedo answered 11/1, 2023 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.