Simple scope π
Get a scoped ID for whatever file youβre in. Resolved at build-time with zero client JS.
Installation
Simple scope is a vite plugin compatible with any vite-based framework (Astro, Nuxt, SvelteKit, etc). First install the dependency from npm:
Then, set up type inferencing for the simple:scope
module with an env.d.ts
file. You can create this file at the base of your project, or add to the provided src/env.d.ts
file for frameworks like Astro:
Finally, apply as a vite plugin in your framework of choice:
Usage
You can import the scope()
utility from simple:scope
in any JavaScript-based file. This function accepts an optional prefix string for naming different scoped identifiers.
Since scope()
uses the file path to generate IDs, multiple calls to scope()
will append the same value:
Simple scope will also generate the same ID when called server-side or client-side. This prevents hydration mismatches when using component frameworks like React or Vue, and is helpful when querying scoped element id
s from the DOM.
This example uses Astro to add a scoped id
to a <canvas>
element, and queries that id
from a client-side <script>
: