首页 > 解决方案 > 未捕获的 ReferenceError:Dojo API 未定义 require

问题描述

我已经看到了这个错误的多个化身,但没有看到与使用 Dojo API/CDN 直接相关的答案。我只是通过一个快速的 Dojo 图表教程来了解如何正确应用饼图。我正在使用简单的说明来设置一个可以用来从本地测试的网页(见下文)。每次我启动.html文件时,我都会收到错误 - Uncaught ReferenceError: require is not defined. 之前的所有答案都指向src错误,无论是cdn、api还是文件路径。我尝试了多种 CDN 和配置,包括src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"

<script data-dojo-config="async: 1"
        src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>`, 

但是我仍然遇到相同的错误(这些直接来自文档)。关于导致此错误的原因以及如何解决它以测试我的简单饼图的任何建议?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Tutorial: Pie Chart!</title>
        <script> src="//ajax.googleapis.com/ajax/libs/dojo/1.13.0/dojo/dojo.js"></script>
    </head>
    <body>
        <script>
            require([
                'dojo/dom',
                'dojo/dom-construct',
                'dojox/charting/Chart',
                'dojox/charting/themes/Claro',
                'dojox/charting/PiePlot'
            ], function (dom, domConstruct, Chart, theme, PiePlot) {
                var pieChart = new Chart("chartNode");

            // Set the theme
            pieChart.setTheme(theme);

            // Add the only/default plot
            pieChart.addPlot("default", {
                type: PiePlot, // our plot2d/Pie module reference as type value
                radius: 200,
                fontColor: "black",
                labelOffset: -20
            });

            // Add the series of data
            pieChart.addSeries("January",chartData);

            // Render the chart!
            pieChart.render();
        });
        </script>
        <div id="chartNode" style="width: 550px; height: 550px;"></div>
    </body>
</html>

标签: javascripthtmldojorequiredojox.charting

解决方案


首先,您的脚本标签第 6 行、封闭标签脚本和脚本标签外的 src 属性中存在类型错误,这就是为什么您有错误 reuire 不是...

同样在更正之后你仍然会有一些错误,

所以你需要修复导入

'dojox/charting/PiePlot'应该替换为'dojox/charting/plot2d/Pie'

你需要在chartData这里声明你的,

如果您需要文件版本,请参阅此GIST

否则请参阅下面的工作片段:

require([
  'dojo/dom',
  'dojo/dom-construct',
  'dojox/charting/Chart',
  'dojox/charting/themes/Claro',
  'dojox/charting/plot2d/Pie'
], function(dom, domConstruct, Chart, theme, PiePlot) {
  
  chartData = [
      { y: 389, text: "data1 " },
      { y: 125, text: "data 2" },
      { y: 285, text: "data 3" },
      { y: 193, text: "data 4" },
       { y: 21, text: "No data" }
  ];

  
  var pieChart = new Chart("chartNode");

  // Set the theme
  pieChart.setTheme(theme);

  // Add the only/default plot
  pieChart.addPlot("default", {
    type: PiePlot, // our plot2d/Pie module reference as type value
    radius: 200,
    fontColor: "black",
    labelOffset: -20
  });

  // Add the series of data
  pieChart.addSeries("January", chartData);

  // Render the chart!
  pieChart.render();
});
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"></script>
<div id="chartNode" style="width: 550px; height: 550px;"></div>


推荐阅读