Using RequireJS to load plotly and D3

前端 未结 3 1184
傲寒
傲寒 2021-01-21 07:22

I am trying to use RequireJS to load the plotly and d3 libraries in my js code. I have tried this:

require.config({
    paths: {
       d3: \'/static/scripts/plo         


        
相关标签:
3条回答
  • 2021-01-21 07:45

    You need a shim for Plotly since it depends on D3, and according to the Plotly docs, it looks like jQuery is also needed. Your config should look like:

    /*
    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...}
    });
    

    In your index.html you should have only a single script tag:

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

    If you want to use D3 and Plotly in another JS file that uses require then you should be using the AMD style:

    /*
    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
        }
    });
    

    Now, you can use foo-bar.js in another module (assuming the two files are on the same directory level):

    define(['./foo-bar'], function(fooBar) {
        console.log(fooBar.foo) // Object
        console.log(fooBar.bar) // function() {}
    });
    
    0 讨论(0)
  • 2021-01-21 07:47

    I had the same problem, it's a defect/oversight in Plotly. The error occurs on the last line of the library itself (plotly.js / plotly.min.js):

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

    I suspect this is a problem with the module pattern being used and the library's own code to detect AMD loaders.

    I was able to workaround it removing the last line, which I'd guess doesn't cause any break in functionality.

    ...:414}]},{},[305])(305)});
    
    0 讨论(0)
  • 2021-01-21 07:48

    Have you tried coupling your third Java script file with these two files. Here is a suggestion:

    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();
    });
    
    0 讨论(0)
提交回复
热议问题