使用RequireJS加载绘图和D3

时间:2015-10-30 12:38:31

标签: javascript d3.js requirejs plotly

我正在尝试使用RequireJS在我的js代码中加载plotly和d3库。我试过这个:

require.config({
    paths: {
       d3: '/static/scripts/plotly/dependencies/d3.v3.min',
       plotly: '/static/scripts/plotly/plotly.min'
    }
}); 
require(['d3'], function(d3) {
    d3();
}); 
require(['plotly'], function(plotly) {
    plotly();
});    

但这不起作用。当我的js函数被调用时,我得到:

Uncaught ReferenceError: plotly is not defined
Uncaught ReferenceError: Plotly is not defined
Uncaught ReferenceError: d3 is not defined
Uncaught TypeError: d3 is not a function

在这种情况下使用RequireJS的正确方法是什么?

使用当前版本的代码更新帖子,但仍无效。

在调用脚本中,我现在有了这个:

require.config({
    paths: {
        heatmap: '/static/scripts/heatmap',
        d3: '/static/scripts/plotly/dependencies/d3.v3.min',
        plotly: '/static/scripts/plotly/plotly.min',
    }
});
require(['d3', 'plotly', 'heatmap'], function(d3, plotly, heatmap) {
    generate_heatmap();
});

它失败了:

Uncaught ReferenceError: Plotly is not defined(anonymous function) @ plotly.min.js:17

函数Plotly(大写P)在plotly.min.js中定义。我是否必须在某处添加对该功能的引用?

3 个答案:

答案 0 :(得分:1)

Plotly需要shim因为它依赖于D3,并且根据Plotly文档,它看起来也需要jQuery。您的配置应如下所示:

/*
main.js file
*/
require.config({
  paths: {
    d3: '/static/scripts/plotly/dependencies/d3.v3.min',
    jquery: '/path/to/jquery',
    plotly: '/static/scripts/plotly/plotly.min'
  },

  shim: {
    plotly: {
      deps: ['d3', 'jquery'],
      exports: 'plotly'
    }
  }
});

require(['d3', 'plotly'], function(d3, plotly) {
  console.log(plotly); // Object {Lib: Object, util: Object...}
  console.log(d3); // Object {version: "3.5.6", behavior: Object...}
});

index.html 中,您应该只有一个脚本标记:

<script data-main="main" src="/path/to/require/folder/require.js"></script>

如果你想在另一个使用require的JS文件中使用D3和Plotly,那么你应该使用AMD风格:

/*
foo-bar.js
*/
define(['d3', 'plotly'], function(d3, plotly) {
    var foo = {};

    function bar() {
       // Some code here...
    }

    // This will allow other modules to use
    // the foo object and the bar function.
    return fooBar {
        foo: foo,
        bar: bar
    }
});

现在,您可以在另一个模块中使用 foo-bar.js (假设这两个文件位于同一目录级别):

define(['./foo-bar'], function(fooBar) {
    console.log(fooBar.foo) // Object
    console.log(fooBar.bar) // function() {}
});

答案 1 :(得分:1)

我遇到了同样的问题,这是Plotly的缺陷/疏忽。错误发生在库本身的最后一行(plotly.js / plotly.min.js):

...:414}]},{},[305])(305)});Plotly.version='1.0.0';

我怀疑这是使用模块模式的问题,以及库自己的代码来检测AMD加载器。

我能够解决它删除最后一行,我认为这不会导致功能中断。

...:414}]},{},[305])(305)});

答案 2 :(得分:0)

您是否尝试将第三个Java脚本文件与这两个文件耦合。这是一个建议:

require.config({
    paths: {
       d3: '/static/scripts/plotly/dependencies/d3.v3.min',
       plotly: '/static/scripts/plotly/plotly.min',
       myfile: '/stattic/scripts/myfile',
    }
});

require(['d3', 'plotly', 'myfile'], function(d3, plotly, myfile) {
    generate_heatmap();
});