【发布时间】:2021-04-04 22:43:43
【问题描述】:
在release 2.9.4 之前,我将 ChartJS 与@types/chart.js 结合使用以获得所有类型的 TypeScript 支持。我使用 Webpack 和 TypeScript 的最小工作示例如下所示:
package.json:
{
"devDependencies": {
"@types/chart.js": "^2.9.31",
"ts-loader": "^8.1.0",
"typescript": "^4.2.3",
"webpack": "^5.30.0",
"webpack-cli": "^4.6.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"chart.js": "^2.9.4"
}
}
tsconfig.json:
{
"compilerOptions": {
"esModuleInterop": true,
},
}
webpack.config.json:
module.exports = {
entry: {
main: "./main.ts",
},
module: {
rules: [
{
test: /\.ts$/,
loader: "ts-loader",
exclude: /node_modules/,
},
],
},
};
main.ts:
import Chart from "chart.js";
new Chart("chart", {
type: 'line',
data: {
labels: ['Label 1', 'Label 2', 'Label 3'],
datasets: [{
label: "Dataset 1",
data: [1, 2, 3],
}]
},
});
index.html:
<!DOCTYPE html>
<html>
<body>
<canvas id="chart"></canvas>
<script src="main.js"></script>
</body>
</html>
但是在更新到version 3.0.0 之后,这不再起作用(我删除了@types/chart.js,因为chart.js 自该版本发布以来提供了自己的类型):
npx webpack serve --mode 开发
ERROR in [...]/chartjs/main.ts
./main.ts 3:4-9
[tsl] ERROR in [...]/chartjs/main.ts(3,5)
TS2351: This expression is not constructable.
Type 'typeof import("[...]/chartjs/node_modules/chart.js/types/index.esm")' has no construct signatures.
但由于内置类Chart 实际上有一个constructor,我并不真正了解问题以及如何解决它。将 ChartJS 版本 3 与 Webpack 和 TypeScript 结合使用的预期方式是什么?
在此先感谢您提供任何将我引向正确方向的提示!
【问题讨论】:
-
您是否导入并注册了控制器、元素、比例和插件? chartjs.org/docs/latest/getting-started/…
-
@uminder 非常感谢,这正是问题所在。考虑到我花了多少时间阅读文档,我现在有点尴尬:) 如果您发表评论作为答案,我会接受。
标签: javascript typescript webpack chart.js chart.js3