我有两个JavaScript文件baseChart.js和chart.min.js。我不想将我的chart.min.js包含到index.html文件中。我只想在我的index.html中包含baseChart.js。

`var s = document.createElement("script");
s.setAttribute("src","js/Chart.min.js");
document.head.appendChild(s);

class BaseChart{

    constructor(area, settings) {

        this.area = area;
        this.settings = settings;
    }
    a() {
        new Chart(this.area, this.settings);
        console.log("BaseChart");
    }
}


class BarChart extends BaseChart {
    constructor(area, settings) {
        super(area, settings);
    }
    /* constructor(ctx) {
        var data = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fill: false,
                    lineTension: 0.1,
                    backgroundColor: "rgba(75,192,192,0.4)",
                    borderColor: "rgba(75,192,192,1)",
                    borderCapStyle: 'butt',
                    borderDash: [],
                    borderDashOffset: 0.0,
                    borderJoinStyle: 'miter',
                    pointBorderColor: "rgba(75,192,192,1)",
                    pointBackgroundColor: "#fff",
                    pointBorderWidth: 1,
                    pointHoverRadius: 5,
                    pointHoverBackgroundColor: "rgba(75,192,192,1)",
                    pointHoverBorderColor: "rgba(220,220,220,1)",
                    pointHoverBorderWidth: 2,
                    pointRadius: 1,
                    pointHitRadius: 10,
                    data: [65, 59, 80, 81, 56, 55, 40],
                    spanGaps: false,
                },
                {
                    label: "Second",
                    data: [12, 56, 45, 23, 78, 23, 90],
                }
            ]
        };
        var lineChart = new Chart(ctx, {
            type: 'line',
            data: data
        });
    } */
    b() {
        super.a();
    }
}`


当前,这是baseChart.js文件,当我尝试运行此代码时,出现错误“未定义图表,因为我使用了'new Chart(this.area,this.settings);'”。并且在调用此方法之前,未初始化chart.min.js。”。我想在初始化此类和方法之前初始化chart.min.js。我使用了chart.js库。所以我该怎么做?

最佳答案

我建议您通过npm安装chart.js

npm install chart.js --save


然后像这样导入它:

// ES6

import Chart from 'chart.js';


我假设您正在使用诸如webpack之类的捆绑程序来使上面的代码起作用。如果不是这样,您必须在baseChart.js之前的索引文件中包含chart.min.js

10-07 18:10
查看更多