javascripttypescriptclassastrojs

Pass frontmatter variables to scripts using data-attribute and use in JavaScript Class


I have the following Astro component:

   ---
    type Props = {
      uuid: string;
    };
    
    const { uuid } = Astro.props;
    ---
    
    <div class="my-feature" data-uuid={uuid} id="my-feature"></div>
    
    <script is:inline src={import.meta.env.MY_SCRIPT}></script>
    
    <script>
      import { MyFeatureHelper } from '@/scripts/my-helper';
    
      let myFeature;
    
      const ref = document.getElementById('my-feature');
    
      myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
        uuid: this?.ref.uuid,
      });
    
      myFeaturer.build();
    
    </script>

I need to pass uuid prop to the <script> tag without define:vars as described here because then my script will be treated as is:inline and I can't import the JavaScript Class MyFeatureHelper, which I need.

How can I get access to uuid and use it like e.g. uuid: this?.ref.uuid, using the data-attribute trick?

How do I get this to work?


Solution

  • See Astro docs where there is an example on how to do this with a basic web component.

    Alternatively, the following should work:

    ---
    type Props = {
      uuid: string;
    };
    
    const { uuid } = Astro.props;
    ---
    
    <div data-uuid={uuid} id="my-feature"></div>
    
    <script>
      const uuid = document.getElementById('my-feature')?.dataset.uuid
    </script>