如何在节点和typescript项目中导入d3.js ?[ERR_REQUIRE_ESM]



我正在使用typescript、oclif和d3.js等工具开发一个节点项目。Typescript是在用oclif创建项目时由npx配置的,所以我没有控制它的所有方面(特别是关于TS,我不是专家)。TS是伟大的,但配置明智,meh)。

无论如何,一切都工作得很好,但我最近添加d3作为一个依赖关系,并试图建立一个文档,我得到这个错误时运行它:

(node:22554) [ERR_REQUIRE_ESM] Error Plugin: dbacl [ERR_REQUIRE_ESM]: require() of ES Module /dbacl/node_modules/d3/src/index.js from /dbacl/src/tree/graph-tree.ts not supported.
Instead change the require of index.js in /Users/nico/Furo/Dev/dbacl/src/tree/graph-tree.ts to a dynamic import() which is available in all CommonJS modules.

在我使用d3的文件中,我按照文档导入它:

import * as d3 from 'd3'

我怀疑这可能是编译后的问题,所以这里是tsconfig.json。自npx生成以来,我没有更改任何内容。

{
"compilerOptions": {
"declaration": true,
"importHelpers": true,
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"target": "es2019",
},
"include": [
"src/**/*"
]
}

如果它更相关,这是我的package.json文件也是(没有改变任何东西):

{
"name": "dbacl",
"version": "0.0.0",
"description": "",
"author": "",
"bin": {
"dbacl": "./bin/run"
},
"license": "MIT",
"main": "dist/index.js",
"repository": "*****/dbacl",
"files": [
"/bin",
"/dist",
"/npm-shrinkwrap.json",
"/oclif.manifest.json"
],
"dependencies": {
"@oclif/core": "^1",
"@oclif/plugin-help": "^5",
"@oclif/plugin-plugins": "^2.0.1",
"@types/d3": "^7.4.0",
"@types/jsdom": "^16.2.14",
"d3": "^7.6.1",
"directory-tree": "^3.3.0",
"jsdom": "^20.0.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"@oclif/test": "^2",
"@types/chai": "^4",
"@types/mocha": "^9.0.0",
"@types/node": "^16.9.4",
"chai": "^4",
"eslint": "^7.32.0",
"eslint-config-oclif": "^4",
"eslint-config-oclif-typescript": "^1.0.2",
"globby": "^11",
"mocha": "^9",
"oclif": "^3",
"shx": "^0.3.3",
"ts-node": "^10.2.1",
"tslib": "^2.3.1",
"typescript": "^4.4.3"
},
"oclif": {
"bin": "dbacl",
"dirname": "dbacl",
"commands": "./dist/commands",
"plugins": [
"@oclif/plugin-help",
"@oclif/plugin-plugins"
],
"topicSeparator": " ",
"topics": {
"hello": {
"description": "Say hello to the world and others"
}
}
},
"scripts": {
"build": "shx rm -rf dist && tsc -b",
"lint": "eslint . --ext .ts --config .eslintrc",
"postpack": "shx rm -f oclif.manifest.json",
"posttest": "yarn lint",
"prepack": "yarn build && oclif manifest && oclif readme",
"test": "mocha --forbid-only "test/**/*.test.ts"",
"version": "oclif readme && git add README.md"
},
"engines": {
"node": ">=12.0.0"
},
"keywords": [
"oclif"
],
"types": "dist/index.d.ts"
}

我发现这个问题很令人困惑,因为我一直在搜索这个问题,似乎我在做正确的事情。我想问题可能出在我的屏幕和椅子之间,但我真的不明白。另外,我应该像这样使用动态导入吗?

const d3 = await import('d3')

我试过了,但没有用。我创建了异步生成文档的函数,并在开始处添加了这一行,但没有。不管怎样,如果我相信这个错误,这就是我要走的路,但我在寻找问题的解决方案时没有看到这个解决方案。你们怎么看?

感谢

所以多亏了同事和本文的输入,问题是d3现在只支持ESM。所以当编译器将导入转换为

// index.ts
import * as d3 from 'd3'
// compiled index.js
const d3 = require('d3')

就是行不通。我使用d3版本7,并快速修复它是降级到版本6.7.0,当它确实支持commonJS。

现在,我必须继续这个项目,但我会继续研究它,并研究如何在我的项目中使用d3的最新版本。如果我做了,我会编辑那个答案!

欢呼

相关内容

最新更新