#How can I use a npm module into a script tag with defined:vars attribute ?

4 messages · Page 1 of 1 (latest)

eager creek
#

I would like to use the ChartJS npm inside a script tag. I am trying to load data into the script tag thanks to the defined:vars attribute. However when I use defined:vars, I cannot access the npm modules anymore.

craggy daggerBOT
#

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:vars on a <script> tag implies the is:inline directive, 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> (without define:vars or 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>
#

This way, you can use npm modules and still pass dynamic data from your frontmatter to your client-side script.
Pass frontmatter variables to scripts

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: