Skip to content

Commit 0732cd4

Browse files
committed
feat(svelte): manually query DOM for chart holder element as fallback
In the rollup configuration, we explicitly define svelte as an external dependency for UMD/ESM targets.
1 parent 825c407 commit 0732cd4

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

Diff for: packages/svelte/rollup.config.js

+3-4
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export default [
1818
resolve(),
1919
terser()
2020
],
21-
external: ["@carbon/charts"]
21+
external: ["svelte", "@carbon/charts"]
2222
},
2323
{
2424
input: "./src/index.js",
@@ -28,9 +28,8 @@ export default [
2828
},
2929
plugins: [
3030
svelte(),
31-
resolve(),
32-
terser()
31+
resolve()
3332
],
34-
external: ["@carbon/charts"]
33+
external: ["svelte", "@carbon/charts"]
3534
}
3635
];

Diff for: packages/svelte/src/BaseChart.svelte

+21-5
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,33 @@
66
import { onMount, createEventDispatcher } from "svelte";
77
88
const dispatch = createEventDispatcher();
9+
const id = "chart-" + Math.random().toString(36);
910
1011
let ref = undefined;
1112
let chart = undefined;
1213
1314
onMount(() => {
14-
chart = new Chart(ref, { data, options });
15-
dispatch("load", chart);
15+
/**
16+
* CodeSandbox does not resolve Svelte components from the `svelte` package.json entry.
17+
* This causes `bind:ref` to be `undefined`; the chart can't mount to the element.
18+
*
19+
* We fallback to manually querying the DOM for the chart holder element because
20+
* CodeSandbox does not use uncompiled Svelte source code.
21+
*
22+
* See https://github.com/sveltejs/svelte/issues/2937
23+
*/
24+
const element = ref || document.getElementById(id);
25+
26+
if (element) {
27+
chart = new Chart(element, { data, options });
28+
dispatch("load", chart);
29+
}
1630
1731
return () => {
18-
chart.destroy();
19-
dispatch("destroy");
32+
if (chart) {
33+
chart.destroy();
34+
dispatch("destroy");
35+
}
2036
};
2137
});
2238
@@ -27,4 +43,4 @@
2743
}
2844
</script>
2945

30-
<div {...$$restProps} bind:this={ref} on:load on:update on:destroy />
46+
<div {...$$restProps} bind:this={ref} {id} />

0 commit comments

Comments
 (0)