@@ -2,55 +2,22 @@ import devtoolsJson from 'vite-plugin-devtools-json';
22import { defineConfig } from 'vitest/config' ;
33import { sveltekit } from '@sveltejs/kit/vite' ;
44import { optimizeCss } from 'carbon-preprocess-svelte' ;
5-
6- import fs from 'fs' ;
7- import type { Plugin , UserConfig } from 'vite' ;
5+ import type { Plugin } from 'vite' ;
86
97/**
10- * Vite plugin to fix @dagrejs/dagre's dynamic require of @dagrejs/graphlib.
11- * From https://github.com/dagrejs/dagre/issues/492#issuecomment-3831937463
12- *
13- * Uses esbuild's onLoad hook during pre-bundling to inject the graphlib import
14- * and replace dynamic require calls before the code is bundled.
15- *
16- * See: https://github.com/dagrejs/dagre/issues/492
8+ * HACK: Fixes issue with the CJS reference to @dagrejs/graphlib in @dagrejs/dagre@^2.
9+ * https://github.com/dagrejs/dagre/issues/492#issuecomment-3853652764
1710 */
1811function dagreGraphlibPlugin ( ) : Plugin {
1912 return {
20- name : 'dagre-graphlib-fix' ,
21- config ( ) : Omit < UserConfig , 'plugins' > {
22- return {
23- optimizeDeps : {
24- esbuildOptions : {
25- plugins : [
26- {
27- name : 'dagre-graphlib-esbuild' ,
28- setup ( build ) {
29- // Intercept the dagre ESM file during pre-bundling
30- build . onLoad ( { filter : / d a g r e \. e s m \. j s $ / } , async ( args ) => {
31- let contents = await fs . promises . readFile ( args . path , 'utf8' ) ;
32-
33- // Add graphlib import at the top
34- const graphlibImport = `import * as __graphlib__ from '@dagrejs/graphlib';\n` ;
35- contents = graphlibImport + contents ;
36-
37- // Replace all dynamic require patterns
38- contents = contents . replace (
39- / g \( \s * [ " ' ] @ d a g r e j s \/ g r a p h l i b [ " ' ] \s * \) / g,
40- '__graphlib__'
41- ) ;
42-
43- return {
44- contents,
45- loader : 'js' as const
46- } ;
47- } ) ;
48- }
49- }
50- ]
51- }
52- }
53- } ;
13+ name : 'dagre-graphlib-plugin' ,
14+ enforce : 'pre' ,
15+ transform ( code , id ) {
16+ if ( ! id . includes ( 'dagrejs' ) || id . includes ( 'graphlib' ) ) return ;
17+ const modifiedCode = `
18+ import * as __graphlib__ from '@dagrejs/graphlib';
19+ ${ code . replace ( / g \( \s * [ " ' ] @ d a g r e j s \/ g r a p h l i b [ " ' ] \s * \) / g, '__graphlib__' ) } ` ;
20+ return { code : modifiedCode , map : null } ;
5421 }
5522 } ;
5623}
@@ -76,5 +43,8 @@ export default defineConfig({
7643 }
7744 }
7845 ]
46+ } ,
47+ optimizeDeps : {
48+ include : [ '@dagrejs/dagre > @dagrejs/graphlib' ]
7949 }
8050} ) ;
0 commit comments