Unable to execute requirejs - d3.sankey due to a non-existent function

I am currently facing an issue while attempting to create a basic sankey diagram using d3 libraries loaded from requirejs. Previously, I had no problems rendering everything with the core d3 library. However, when trying to incorporate d3-sankey in this particular case, it does not seem to be working as expected. I have experimented with the shim configuration but still can't pinpoint the exact source of the problem. Whenever I try to run the provided code, I encounter the error 'Uncaught TypeError: d3.sankey is not a function'.

My suspicion is that the loading sequence of the libraries might be causing the issue, but I am uncertain about how to address it. Can anyone offer assistance?

Codepen - https://codepen.io/quirkules/pen/wYoXxQ

// define URLs
require.config({
  paths: {
    cloudflare: 'https://cdnjs.cloudflare.com/ajax/libs'
  },
  map: {
    '*': {
      'd3': 'cloudflare/d3/4.8.0/d3',
      'd3-timer': 'cloudflare/d3-timer/1.0.5/d3-timer',
      'd3-array': 'cloudflare/d3-array/1.2.2/d3-array',
      'd3-collection': 'cloudflare/d3-collection/1.0.5/d3-collection',
      'd3-interpolate': 'cloudflare/d3-interpolate/1.3.0/d3-interpolate',
      'd3-color': 'cloudflare/d3-color/1.2.1/d3-color',
      'd3-shape': 'cloudflare/d3-shape/1.2.0/d3-shape',
      'd3-path': 'cloudflare/d3-path/1.0.5/d3-path',
      'd3-sankey': 'cloudflare/d3-sankey/0.7.1/d3-sankey'
    }
  },
  shim : {
    d3 : {
      exports : 'd3'
    },
    'd3-sankey' : {
      deps: ['d3']
    }
  }
});

// load d3
require(['d3', 'd3-timer', 'd3-array', 'd3-collection', 'd3-interpolate', 'd3-color', 'd3-shape', 'd3-sankey'], function(d3) {
  //****** CREATE DIVS ******//

  // Add the divs to the DOM
  $(document.body)
    .append('<div id="header"></div>')
    .append('<div id="chart"></div>')
    .append('<div id="footer"></div>');
  //add text to the divs
  document.getElementById("header").innerHTML = '<b>Title</b>';

  // set the dimensions and margins of the graph
  var margin = { top: 20, right: 20, bottom: 40, left: 50 },
    width = d3.select('#chart').node().getBoundingClientRect().width - margin.left - margin.right,
    height = d3.select('#chart').node().getBoundingClientRect().height - margin.top - margin.bottom;

  //
  var svg = d3.select("#chart")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);
  var g = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var graph = d3.sankey()
    .nodeWidth(15)
    .nodePadding(10)
    .size([width, height]);

  var path = graph.link();

  var freqCounter = 1;

  //****** END CREATE CHART ******//
});

Answer №1

Reasons for Utilizing require Function?

When attempting to load the two scripts below, an issue arises at the line var path = graph.link();, indicating that d3.sankey is recognized as a function.

To rectify this problem, eliminate the usage of require and incorporate:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-sankey/0.7.1/d3-sankey.min.js"></script>

d3.js encompasses most additional modules except for d3-sankey. Strangely, d3.js fails to register its internal modules with require(), prompting the loading of separate modules like d3-array, d3-collection, d3-shape, d3-path.

It's plausible that there may be a version compatibility dilemma - how can one ascertain which module versions are compatible with d3.v4.8.0?

Revision

If I invoke d3-sankey subsequent to loading other modules, the error dissipates. However, it remains uncertain if this approach will be effective in the long run (hyperlinks are omitted due to absence of data handled by sankey).

require(['d3-selection', 'd3-timer', 'd3-array', 'd3-collection', 'd3-interpolate', 'd3-color', 'd3-shape'], function(d3) {
require(['d3-sankey'], function(dsankey) {
  //****** CREATE DIVS ******//
  // .....
  var graph = dsankey.sankey()
    .nodeWidth(15)
    .nodePadding(10)
    .size([width, height]);
  //****** END CREATE CHART ******//
});
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

optimal method for displaying HTML strings with components in Vue

My website is a Blog/News site featuring posts that contain HTML content stored in the database. In addition to posts, I also want to include elements like sliders which cannot be generated using v-html. I explored Vue's Render Functions to find a so ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Launching JQuery modal upon button click

I'm encountering an issue with jQuery Mobile. Here is the JSFiddle link: http://jsfiddle.net/Gc7mR/3/ Initially, I have a Panel containing multiple buttons. The crucial button has an id of 'define'. <div data-role=header data-position= ...

What is the reason that server.js is always excluded from the Webpack build process?

I am currently utilizing Vue.js 3 for the front end of my application, while employing Node/Express for the back-end. My goal is to implement server side rendering, but I have encountered some challenges along the way. As far as I can tell, the client-sid ...

Listener for a special event in Three.js

As I embark on my journey with Three js, I find myself in search of a unique event listener that seems to elude me online. I am curious whether it is feasible to execute a specific action when the first-person viewer enters an object. Any advice would be ...

Multiple 'keydown' events are accumulating with Ajax activated

When the search field is focused, I am loading JSON into the browser and then iterating over the JSON objects to find real-time results 'on keydown'. The issue I'm encountering is detailed in the console after the initial block of code Aja ...

Is there a way to eliminate the feature that rearranges characters in reverse order?

Is there a way to modify this code to only replace vowels with "er" instead of reversing the order of characters? I'm hoping to remove the function that reverses the character order. If you want to take a look at the code, it's available on Past ...

Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error Uncaught SyntaxError: Unexpected token ). This error is displayed in the console of the chrome browser as VM80623:1 Uncaught SyntaxError: Unexpected token ). Cl ...

What is the best approach: Referencing schema within properties or including it as an array in Mongoose?

Consider the scenario where we have two schemas, User and Post. Should we include a reference to User in Post's properties or should we add an array of Post schema inside User schema? Which approach is more efficient in terms of performance and other ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

Is it possible to nest Route components in react-router version 4.x?

How can one properly implement nested routes in react-router version 4.x? Previous methods like the one below worked well, but upgrading to version 4.x now results in a warning... <Route path='/stuff' component={Stuff}> <Route path=&a ...

The UI Router template fails to inject despite state changes occurring

I've been attempting to create nested views, you can check out the Plunker demo https://embed.plnkr.co/oRMnMW4QoWwhSkm9maHf/. The state is updating as expected but the template remains the same. Could someone please point out where I may have gone wr ...

Is it possible for a div with fixed position to still have scrolling functionality

My fixed positioned div (#stoerer) appears to be moving while scrolling, although it is just an optical illusion. Check out this visual explanation: view gif for clarification Below is the code snippet in question: <div id="stoerer"> <button ...

`What is the best way to extract elements from a table once all components have been fully rendered using React and testing-library/react?`

Attempting to properly test my UsersTable page in React has presented a challenge, as the testing library seems to access the elements before they have had a chance to render. Please review the code snippet below: UsersTable.js import React, { useState, u ...

Vector indicating the direction of a rotation in Three.js

I am in the process of rotating an arrow on the surface of a planet to align with the direction of its travel. I have the direction vector and the up vector from the surface normal. How can I convert this into a quaternion for the rotation of my arrow? I a ...

Quick guide on establishing a remote websocket connection to a Node.js server hosted on Heroku

I am facing issues while trying to establish a connection with a nodejs server using a websocket. Despite my efforts, I have not been successful. The server.js file in question appears as follows: var app = require('express')(); var http = req ...

Changing the hue of individual pixels on an HTML canvas to a different color while maintaining their original shading

I have created a function that enables me to draw an image on a hidden canvas temporarily in order to modify colors and change everything except solid black to a specific color while preserving the original white "shade". However, when attempting to execu ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...