#Conditionally import package in script tag
1 messages · Page 1 of 1 (latest)
Hi @arctic folio. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Based on the information extracts provided, Astro doesn't support conditional imports directly within a <script> tag. However, you can conditionally import an NPM package in your Astro component's frontmatter and then use it within a <script> tag. Here's an example:
---
import confetti from 'canvas-confetti';
let shouldImportConfetti = type === 'video';
---
{shouldImportConfetti && <p>test</p>}
<script>
// Import npm modules conditionally.
if ({shouldImportConfetti}) {
const confetti = {confetti};
}
// Your other JavaScript code here
</script>
In this example, we import the confetti package in the frontmatter and set a variable shouldImportConfetti based on the type value. Then, we conditionally assign the imported confetti package to a constant within the <script> tag.
Remember to replace the example package and condition with your desired package and condition.