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

With the Simple Query Astro integration

Simple Scope is included with the Simple Query Astro integration. You can apply this integration using the astro add CLI:

Terminal window
astro add simple-stack-query

If you do not want to use Simple Query, install as a vite plugin with the following instructions.

As a vite plugin

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, 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>