Graphology: JavaScript Graph Library
Graphology is a comprehensive JavaScript library providing a robust and multipurpose Graph object. It implements a unified specification for various graph types, including directed, undirected, multi, and mixed graphs, making it a versatile tool for network analysis and graph theory applications. The library focuses on performance and memory efficiency, particularly when handling complex multigraph structures. The current stable version is 0.26.0, which introduced explicit ESM support and removed some internal dependencies. Releases are made periodically, incorporating performance enhancements, new features like additional degree methods, and refinements to its internal architecture. It distinguishes itself by offering a well-defined and consistent API for graph manipulation.
Common errors
-
TypeError: Graph is not a constructor
cause Attempting to use `require('graphology')` to import the `Graph` class in an environment that enforces ESM-style imports, or when the package's `package.json` entry points prioritize ESM.fixChange the import statement to `import Graph from 'graphology';` for ESM compatibility. If using TypeScript, ensure your `tsconfig.json`'s `module` option is set correctly (e.g., `"ESNext"` or `"NodeNext"`). -
TS2307: Cannot find module 'graphology' or its corresponding type declarations.
cause TypeScript compiler cannot locate the type definitions for `graphology`.fixInstall the peer dependency `graphology-types`: `npm install --save-dev graphology-types` or `yarn add -D graphology-types`. Ensure `tsconfig.json` includes `node_modules/@types` in `typeRoots` or that type declaration files are correctly resolved. -
Error: The given graph is not multi.
cause Attempting to add multiple edges between the same two nodes in a non-multi graph, or other multi-graph specific operations on a simple graph.fixWhen creating the graph, explicitly set the `multi` option to `true`: `new Graph({ multi: true });` if you intend to allow multiple edges between the same nodes.
Warnings
- breaking Graphology v0.26.0 introduced explicit ESM support. Projects using CommonJS `require()` might encounter module resolution errors or unexpected behavior, especially in modern Node.js environments or bundlers. The library primarily targets ESM.
- breaking The undocumented methods `#.upgradeToMixed` and `#.upgradeToMulti` were removed in v0.24.0. Code relying on these internal methods will break.
- breaking As of v0.26.0, `graphology` no longer shims `Array.from`. This means that environments lacking native `Array.from` support (e.g., very old browsers or Node.js versions) will require a polyfill if `graphology`'s internal operations depend on it.
- gotcha Internal refactoring of edge & neighbor iteration schemes and index handling in v0.24.0 might lead to subtle behavioral changes or performance differences, especially in complex use cases involving self-loops or multigraphs, although no direct API breaks were documented.
Install
-
npm install graphology -
yarn add graphology -
pnpm add graphology
Imports
- Graph
const Graph = require('graphology');import Graph from 'graphology';
- Graph type
import type Graph from 'graphology';
- Specific graph factory (e.g., DirectedGraph)
import { DirectedGraph } from 'graphology';import Graph from 'graphology'; const directedGraph = new Graph({ type: 'directed' });
Quickstart
import Graph from 'graphology';
interface NodeAttributes {
label: string;
}
interface EdgeAttributes {
weight: number;
}
// Create a new directed graph
const graph = new Graph<NodeAttributes, EdgeAttributes, any>({
type: 'directed',
multi: false
});
// Add nodes with attributes
graph.addNode('A', { label: 'Node A' });
graph.addNode('B', { label: 'Node B' });
graph.addNode('C', { label: 'Node C' });
// Add edges with attributes
graph.addEdge('A', 'B', { weight: 1 });
graph.addEdge('B', 'C', { weight: 2 });
graph.addEdge('C', 'A', { weight: 3 });
// Check graph properties
console.log(`Number of nodes: ${graph.order}`);
console.log(`Number of edges: ${graph.size}`);
// Iterate over nodes and their attributes
console.log('Nodes:');
graph.forEachNode((node, attributes) => {
console.log(`- ${node} (Label: ${attributes.label})`);
});
// Iterate over edges and their attributes
console.log('Edges:');
graph.forEachEdge((edge, attributes, source, target) => {
console.log(`- ${source} -> ${target} (Weight: ${attributes.weight})`);
});
// Get neighbors of a node
const neighborsOfB = graph.neighbors('B');
console.log(`Neighbors of B: ${neighborsOfB.join(', ')}`);
// Check if node exists
console.log(`Does node 'D' exist? ${graph.hasNode('D')}`);