当从服务器端渲染图表时, d3函数在node.js中不工作



libraries &模块+它们的版本。

d3: ^7.0.0
dotenv: ^10.0.0
express: ^4.17.1
jsdom: ^16.6.0

我正在尝试在服务器端渲染图表并将其发送到客户端。

我遇到的问题是d3。[不管这里是什么函数]给了我如下所示的错误。

但是,如果我在导入模块后使用console.log(d3),我将获得整个承诺

const d3 = import("d3-selection");
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const document = new JSDOM().window.document;
function getBarChart(){
/* some code here runs perfectly */
d3.select(document.body) // ERROR THROWN HERE.
.append("div")
.attr("id", params.parentID)
.call(chart.render.bind(chart)); // rest of code is similar to this.
/* some code here runs perfectly */
}

错误信息:

TypeError: d3.select is not a function
at getBarChart (D:Github repositoriesdata-viz-projectserversrcbarchartbarchartgenerator.js:34:8)
at D:Github repositoriesdata-viz-projectroutesapisvg.js:10:5
at Layer.handle [as handle_request] (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterlayer.js:95:5)
at next (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterlayer.js:95:5)
at D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterindex.js:335:12)
at next (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterindex.js:275:10)
at Function.handle (D:Github repositoriesdata-viz-projectnode_modulesexpresslibrouterindex.js:174:3)

然而,这是我得到当我console.log(d3)

Promise {
[Module: null prototype] {
create: [Function: default],
creator: [Function: default],
local: [Function: local],
matcher: [Function: default],
namespace: [Function: default],
namespaces: {
svg: 'http://www.w3.org/2000/svg',
xhtml: 'http://www.w3.org/1999/xhtml',
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace',
xmlns: 'http://www.w3.org/2000/xmlns/'
},
pointer: [Function: default],
pointers: [Function: default],
select: [Function: default],
selectAll: [Function: default],
selection: [Function: selection],
selector: [Function: default],
selectorAll: [Function: default],
style: [Function: styleValue],
window: [Function: default]
}
}

我做错了什么?据我所知,当d3为空时,它会返回这样一个错误。但它不是。

您正在使用动态导入,这里可能不需要。只要使用"normal"就可以了。:

import d3 from "d3-selection";
import jsdom  from "jsdom";

动态导入返回一个解析到模块内容的承诺。当你只在某些条件下需要加载某些模块时,可以使用这个。

在您的示例中,您希望始终导入这两个依赖项,因此您只需使用如上所示的静态导入。


显然整个项目使用CommonJS,所以你需要使用require()而不是import(无论你是使用静态版本还是动态版本)。

edit:d3现在似乎使用ESM,所以不应该再使用CommonJS方法了。

最新更新