π Simple scope
Get a scoped ID for whatever file youβre in. Resolved at build-time with zero client JS.
import { scope } from 'simple:scope';
function Form() { return ( <form> <label htmlFor={scope('email')}>Email</label> <input id={scope('email')} name="email" /> </form> );}
/*Output:
<form> <label for="email-dj23i_ka">Email</label> <input id="email-dj23i_ka" name="email"></form>*/Installation
Simple scope is a vite plugin compatible with any vite-based framework (Astro, Nuxt, SvelteKit, etc). First install the dependency from npm:
npm i vite-plugin-simple-scopeThen, apply as a vite plugin in your framework of choice:
import simpleScope from 'vite-plugin-simple-scope';
// apply `simpleScope()` to your vite plugin configFinally, import the ambient types for the simple:scope module. You can update your vite-env.d.ts file in plain Vite projects, or your project-specific ambient types file in frameworks like Astro.
/// <reference types="vite-plugin-simple-scope/types" />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:
scope(); // JYZeLezUscope('first'); // first-JYZeLezUscope('second'); // second-JYZeLezUSimple 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 ids 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>:
---// Server-side templateimport { scope } from 'simple:scope';---
<canvas id={scope('canvas')}></canvas>
<script>// Client-side scriptimport { scope } from 'simple:scope';
const canvas = document.getElementById(scope('canvas'));</script>