#How can I use a npm module into a script tag with defined:vars attribute ?
4 messages · Page 1 of 1 (latest)
Hi @eager creek. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
You cannot use npm modules (like ChartJS) inside a <script> tag that uses the define:vars attribute in Astro. This is because using define:vars on a <script> tag implies the is:inline directive, which disables Astro’s script processing, bundling, and npm import resolution. Inline scripts are rendered directly into the HTML and cannot use ESM imports or npm packages—they only have access to what’s available in the browser environment, not your project’s node_modules.
From the documentation:
Using
define:varson a<script>tag implies theis:inlinedirective, which means your scripts won’t be bundled and will be inlined directly into the HTML.For scripts, try passing variables to scripts manually instead.
Script & Style Directives – define:vars
Recommended approach:
- Import ChartJS in a processed
<script>(withoutdefine:varsor any other attribute). - Pass your data from frontmatter to the script using
data-*attributes on an HTML element, then read those values in your script using the DOM API.
Example:
---
// In your frontmatter
const chartData = { /* ... */ };
---
<canvas id="myChart" data-chart={JSON.stringify(chartData)}></canvas>
<script>
import Chart from 'chart.js/auto';
const ctx = document.getElementById('myChart').getContext('2d');
const data = JSON.parse(document.getElementById('myChart').dataset.chart);
new Chart(ctx, { type: 'bar', data });
</script>