Skip to content

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:

Terminal window
npm i vite-plugin-simple-scope

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:

env.d.ts
/// <reference types="vite-plugin-simple-scope/types" />

Finally, apply as a vite plugin in your framework of choice:

import simpleScope from 'vite-plugin-simple-scope';
// apply `simpleScope()` to your vite plugin config

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:

example.js
scope(); // JYZeLezU
scope('first'); // first-JYZeLezU
scope('second'); // second-JYZeLezU

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 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 template
import { scope } from 'simple:scope';
---
<canvas id={scope('canvas')}></canvas>
<script>
// Client-side script
import { scope } from 'simple:scope';
const canvas = document.getElementById(scope('canvas'));
</script>