npm packages

Client packages are prebundled with rolldown, tree-shaken to the names you import, and preloaded like app modules. Every byte counts in the page size, so the sizes below are the ones that matter.

Install, list, import

Any package manager works: pragma reads package.json and node_modules/. A client import must be listed under dependencies, use a quoted specifier and name what it takes. These are the three packages this page runs.

~/pragma/site
npm i valibot es-toolkit dayjs --ignore-scripts

added 3 packages, and audited 5 packages in 999ms

found 0 vulnerabilities
grep -A6 dependencies package.json
  "dependencies": {
    "dayjs": "^1.11.23",
    "es-toolkit": "^1.53.2",
    "highlight.js": "^11.12.0",
    "valibot": "^1.5.0"
  }

Each package becomes one file, /assets/npm/<package>-<hash>.js (@date-fns/tz turns into date-fns__tz), and code shared between packages goes to /assets/npm/_*.js. Pages that import it get a modulepreload for it. process.env.NODE_ENV is replaced with "production" in builds and "development" in dev.

Tree shaking, measured: highlight.js on this site

The code blocks on this site are colored by highlight.js. Importing the package index pulls in all 193 languages. Importing highlight.js/lib/core plus the three grammars the site needs is 95% less gzip: the 190 unused language modules are dropped. The core itself is not shaken: its ESM entry re-exports CommonJS, and CommonJS ships whole.

The smallest chunk is the one the browser never loads. Every showcase tokenizes in load: _source.server.js runs highlight.js on Node and sends each line with its color ranges, the section pages use ssr = true, and the mount(el) of c-showcase paints the ranges with the CSS Custom Highlight API. The code is in the first HTML and gets its colors when the component mounts, with no extra download. The client chunk exists only for the SEO page's response view, which loads it with import(); lazy chunks are not preloaded and do not count in the page size.

routes/examples/_source.server.js

import sources from '../../utils/sources.json' with { type: 'json' }import { markLines } from '../../utils/highlight.js'const languageByExtension = { html: 'html', xml: 'html', js: 'javascript', json: 'javascript', css: 'css' }const phoneColumns = 36const longSourceRows = 16function joinPath(folder, entry) {  const stack = []  for (const part of (folder + '/' + entry).split('/')) {    if (!part || part === '.') continue    if (part === '..') stack.pop()    else stack.push(part)  }  return stack.join('/')}function baseName(path) {  return path.slice(path.lastIndexOf('/') + 1)}function dirName(path) {  const index = path.lastIndexOf('/')  return index === -1 ? '.' : path.slice(0, index)}function camelCase(name) {  return name.replace(/-(\w)/g, (dash, letter) => letter.toUpperCase())}function phoneRows(lines) {  return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(line.text.length / phoneColumns)), 0)}function languageOf(fileName) {  return languageByExtension[fileName.split('.').pop()] ?? 'text'}async function readSource(folder, entry, example, index) {  const path = joinPath(folder, entry)  const raw = sources[path]  if (raw === undefined) throw new Error('missing bundled source: ' + path)  const code = raw.trimEnd().replaceAll('\t', '  ')  const lines = markLines(code, languageOf(entry))  return {    id: 'source-' + example + '-' + index,    name: baseName(path),    dir: dirName(path) + '/',    path,    lines,    long: phoneRows(lines) > longSourceRows,    active: index === 0,    expanded: false,  }}export async function readExamples(folder, examples) {  const entries = await Promise.all(Object.entries(examples).map(async ([example, sources]) => {    const files = await Promise.all(sources.map((entry, index) => readSource(folder, entry, example, index)))    return [camelCase(example), { files }]  }))  return Object.fromEntries(entries)}

utils/highlight.js

import highlighter from 'highlight.js/lib/core'import xml from 'highlight.js/lib/languages/xml'import javascript from 'highlight.js/lib/languages/javascript'import css from 'highlight.js/lib/languages/css'import { plainLines, codeKinds } from './code-lines.js'highlighter.registerLanguage('html', xml)highlighter.registerLanguage('javascript', javascript)highlighter.registerLanguage('css', css)const cache = new Map()const sigils = new Set(['@', '$', '.'])const blockTags = new Set(['if', 'else-if', 'else', 'for', 'empty'])const maxIndent = 16const interpolation = /(^|[^\\])\{[$\w][\w.$]*\}/gconst kindOfScope = {  'hl-keyword': 'keyword', 'hl-built_in': 'keyword', 'hl-literal': 'keyword',  'hl-string': 'string', 'hl-regexp': 'string', 'hl-symbol': 'string',  'hl-number': 'number',  'hl-name': 'tag', 'hl-selector-tag': 'tag', 'hl-selector-class': 'tag', 'hl-selector-id': 'tag', 'hl-selector-pseudo': 'tag',  'hl-attr': 'attribute', 'hl-attribute': 'attribute', 'hl-property': 'attribute',  'hl-title': 'title', 'hl-variable': 'title', 'hl-params': 'title',  'hl-comment': 'comment', 'hl-meta': 'comment',  'hl-tag': 'punctuation', 'hl-punctuation': 'punctuation', 'hl-operator': 'punctuation',  'hl-directive': 'directive', 'hl-block': 'directive',  'hl-component': 'component',}function refineKind(kind, text) {  if (kind === 'hl-attr' && /^[:@.]/.test(text)) return 'hl-directive'  if (kind === 'hl-name' && blockTags.has(text)) return 'hl-block'  if (kind === 'hl-name' && /^[cp]-/.test(text)) return 'hl-component'  return kind}function scopeClass(scope) {  return scope ? 'hl-' + scope.split('.')[0].replace('language:', 'lang-') : 'hl-plain'}function collectTokens(node, inheritedScope, pushText) {  if (typeof node === 'string') return pushText(node, inheritedScope)  const scope = node.scope && !node.scope.startsWith('language:') ? node.scope : inheritedScope  for (const child of node.children) collectTokens(child, scope, pushText)}function splitIntoLines(rootNode) {  const lines = [{ id: 'line-1', tokens: [] }]  const pushText = (text, scope) => {    text.split('\n').forEach((segment, index) => {      if (index > 0) lines.push({ id: 'line-' + (lines.length + 1), tokens: [] })      if (segment) pushToken(lines.at(-1), segment, scopeClass(scope))    })  }  collectTokens(rootNode, '', pushText)  return lines}function pushToken(line, text, kind) {  const previous = line.tokens.at(-1)  const sigil = previous?.text.slice(-1)  if (kind === 'hl-attr' && sigils.has(sigil)) {    previous.text = previous.text.slice(0, -1)    if (!previous.text) line.tokens.pop()    text = sigil + text  }  kind = refineKind(kind, text)  const last = line.tokens.at(-1)  if (last?.kind === kind) last.text += text  else line.tokens.push({ id: line.id + '-' + line.tokens.length, text, kind })}export function highlightLines(code, language) {  const cacheKey = language + '\n' + code  if (cache.has(cacheKey)) return cache.get(cacheKey)  const result = highlighter.getLanguage(language) ? highlighter.highlight(code, { language, ignoreIllegals: true }) : null  const lines = result ? splitIntoLines(result._emitter.rootNode) : plainLines(code)  cache.set(cacheKey, lines)  return lines}function marksOf(tokens) {  const marks = []  let column = 0  for (const token of tokens) {    const kind = codeKinds.indexOf(kindOfScope[token.kind])    if (kind >= 0 && token.text.trim()) marks.push(column, column + token.text.length, kind)    column += token.text.length  }  return marks}function interpolationMarks(text) {  const directive = codeKinds.indexOf('directive')  return [...text.matchAll(interpolation)].flatMap(found => [found.index + found[1].length, found.index + found[0].length, directive])}export function markLines(code, language) {  let embedded = false  return highlightLines(code, language).map((line, index) => {    const text = line.tokens.map(token => token.text).join('')    const spaces = Math.min(text.length - text.trimStart().length, maxIndent)    const indent = spaces - (spaces % 2)    const marks = marksOf(line.tokens)    if (/^\s*<(script|style)\b/.test(text)) embedded = true    if (language === 'html' && !embedded) marks.push(...interpolationMarks(text))    if (/<\/(script|style)>/.test(text)) embedded = false    return { n: index + 1, text, indent: text.trim() && indent ? indent : null, marks }  })}

lib/components/showcase/showcase.html

<script>  import { log } from 'pragma'  import { codeKinds } from '../../../utils/code-lines.js'  export let source = null  export let caption = ''  const copyResetMs = 1800  const beatGapMs = 400  const timedWindowMs = 1000  const interactions = ['pointerdown', 'click', 'keydown', 'input', 'change', 'submit']  let activeId = ''  let expanded = false  let copiedId = ''  let blockedId = ''  let resetTimer = 0  let announcement = ''  let patches = ''  let beat = ''  const currentId = () => activeId || source.files[0]?.id  const expandedText = () => (expanded ? 'true' : 'false')  const lineCount = file => (file.lines.length === 1 ? '1 line' : file.lines.length + ' lines')  const rows = () => source.files.map(file => ({    file,    active: file.id === currentId(),    pressed: file.id === currentId() ? 'true' : 'false',    copied: file.id === copiedId,    blocked: file.id === blockedId,    lineCount: lineCount(file),  }))  function select(file) {    activeId = file.id  }  function toggleExpanded() {    expanded = !expanded  }  async function copy(file, el) {    clearTimeout(resetTimer)    try {      await navigator.clipboard.writeText(file.lines.map(line => line.text).join('\n'))      copiedId = file.id      blockedId = ''      announcement = `Copied ${file.name}, ${lineCount(file)}.`    } catch (failure) {      log.warn('source copy failed', { 'file.path': file.path, 'exception.message': failure.message })      getSelection()?.selectAllChildren(el.closest('.showcase-file').querySelector('pre'))      copiedId = ''      blockedId = file.id      announcement = `The clipboard is blocked. The code of ${file.name} is selected: copy it with the keyboard.`    }    resetTimer = setTimeout(() => {      copiedId = ''      blockedId = ''      announcement = ''    }, copyResetMs)  }  function highlightFor(kind) {    const name = 'code-' + codeKinds[kind]    if (!CSS.highlights.has(name)) {      const highlight = new Highlight()      highlight.priority = codeKinds[kind] === 'directive' ? 1 : 0      CSS.highlights.set(name, highlight)    }    return CSS.highlights.get(name)  }  function paint(root) {    if (!globalThis.CSS?.highlights) return () => {}    const painted = []    for (const code of root.querySelectorAll('pre[id]')) {      const file = source.files.find(candidate => candidate.id === code.id)      code.querySelectorAll('.code-line').forEach((line, index) => {        const marks = file?.lines[index]?.marks ?? []        if (!line.firstChild) return        for (let i = 0; i < marks.length; i += 3) {          const range = new StaticRange({ startContainer: line.firstChild, startOffset: marks[i], endContainer: line.firstChild, endOffset: marks[i + 1] })          highlightFor(marks[i + 2]).add(range)          painted.push([marks[i + 2], range])        }      })    }    return () => {      for (const [kind, range] of painted) highlightFor(kind).delete(range)    }  }  function formatMs(elapsedMs) {    if (elapsedMs < 0.1) return '<0.1 ms'    return (elapsedMs < 10 ? elapsedMs.toFixed(1) : Math.round(elapsedMs)) + ' ms'  }  function describePatch(count, elapsedMs) {    const updated = count === 1 ? '1 update' : count + ' updates'    return elapsedMs === null ? updated : updated + ' · ' + formatMs(elapsedMs)  }  function watch(stage) {    let interactedAt = 0    let beatAt = 0    const noteInteraction = event => {      if (stage.contains(event.target)) interactedAt = event.timeStamp    }    const observer = new MutationObserver(records => {      if (!beatAt && !interactedAt) return      const touched = new Set(records.map(record => record.target.nodeType === Node.ELEMENT_NODE ? record.target : record.target.parentElement))      touched.delete(null)      const now = performance.now()      const timed = interactedAt > 0 && now - interactedAt < timedWindowMs      const next = describePatch(touched.size, timed ? now - interactedAt : null)      const pulse = now - beatAt > beatGapMs      interactedAt = 0      if (pulse) beatAt = now      if (!pulse && next === patches) return      patches = next      if (pulse) beat = beat === 'a' ? 'b' : 'a'    })    observer.observe(stage, { subtree: true, childList: true, attributes: true, characterData: true })    for (const type of interactions) document.addEventListener(type, noteInteraction, true)    return () => {      observer.disconnect()      for (const type of interactions) document.removeEventListener(type, noteInteraction, true)    }  }  function mount(el) {    const unpaint = paint(el)    const stage = el.querySelector('.showcase-stage')    const unwatch = stage.querySelector('[data-c="frame"]') ? () => {} : watch(stage)    return () => {      clearTimeout(resetTimer)      unpaint()      unwatch()    }  }</script><figure class="overflow-hidden rounded-xl border border-line bg-sunken" .is-expanded="$expanded">  <if page.error>    <p class="px-4 py-5 font-mono text-xs text-error" role="alert">{page.error.message}</p>  </if>  <else>    <div class="flex min-w-0 flex-col">      <div class="flex flex-wrap border-b border-line" role="group" aria-label="Source files">        <for row in $rows key=row.file.id>          <button type="button" class="showcase-tab relative flex-none cursor-pointer border-r border-b border-line px-3.5 py-3 font-mono text-xs transition-colors hover:text-ink" .is-active="row.active" :aria-pressed="row.pressed" :aria-controls="row.file.id" @click="select(row.file)">{row.file.name}</button>        </for>      </div>      <div class="flex min-h-0 flex-1 flex-col">        <for row in $rows key=row.file.id>          <div class="showcase-file min-h-0 min-w-0 flex-1 flex-col" .is-active="row.active" .is-long="row.file.long">            <div class="flex items-center justify-between gap-4 pt-1 pr-1 pl-4">              <p class="showcase-path min-w-0 truncate text-left font-mono text-xs text-faint"><span class="showcase-path-text">{row.file.dir}<span class="text-muted">{row.file.name}</span></span></p>              <button type="button" class="showcase-copy inline-flex min-h-9 flex-none cursor-pointer items-center gap-2 px-2.5 font-mono text-xs" .is-done="row.copied" .is-blocked="row.blocked" @click="copy(row.file, el)">                <svg class="showcase-copy-icon size-3.5" viewBox="0 0 16 16" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="8" fill="none" stroke="currentColor"></rect><path d="M10.5 3.5v-1h-8v8h1" fill="none" stroke="currentColor"></path></svg>                <svg class="showcase-check-icon size-3.5" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3 3 7-7" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="square"></path></svg>                <span class="showcase-copy-idle">Copy <span class="sr-only">{row.file.name}</span></span>                <span class="showcase-copy-done">Copied {row.lineCount}</span>                <span class="showcase-copy-blocked">Code selected</span>              </button>            </div>            <pre class="showcase-code" :id="row.file.id" tabindex="0" :aria-label="row.file.path"><code><for line in row.file.lines key=line.n><span class="code-line" :data-indent="line.indent">{line.text}</span></for></code></pre>            <button type="button" class="showcase-expand h-11 w-full cursor-pointer items-center justify-center border-t border-line font-mono text-xs text-muted hover:text-ink" :aria-expanded="$expandedText" :aria-controls="row.file.id" @click="toggleExpanded"><span class="showcase-expand-more">Show all {row.file.lines.length} lines</span><span class="showcase-expand-less">Show fewer lines</span></button>          </div>        </for>      </div>      <p class="sr-only" role="status">{$announcement}</p>    </div>  </else>  <div class="showcase-live flex min-w-0 flex-col">    <p class="flex min-h-11 items-center gap-2 whitespace-nowrap border-b border-line bg-ground px-4 text-sm text-faint"><span class="showcase-dot size-1.5 flex-none bg-accent" aria-hidden="true" :data-beat="$beat"></span>Live result<span class="ml-auto min-w-0 truncate font-mono text-xs tabular-nums text-muted" aria-hidden="true">{$patches}</span></p>    <div class="showcase-stage"><slot></slot></div>  </div>  <figcaption class="col-span-full border-t border-line px-4 py-3 text-sm text-muted">{$caption}</figcaption></figure><style>  [data-c="showcase"] {    display: grid;    grid-template-columns: minmax(0, 1fr);  }  [data-c="showcase"] .showcase-tab {    margin-bottom: -1px;    color: var(--color-faint);  }  [data-c="showcase"] .showcase-tab.is-active {    background: var(--color-ground);    color: var(--color-ink);  }  [data-c="showcase"] .showcase-tab.is-active::after {    content: "";    position: absolute;    inset: auto 0 -1px;    height: 1px;    background: var(--color-accent);  }  [data-c="showcase"] :is(.showcase-tab, .showcase-copy, .showcase-expand, .showcase-code):focus-visible { outline-offset: -3px; }  [data-c="showcase"] .showcase-file.is-active { display: flex; }  [data-c="showcase"] .showcase-path { direction: rtl; }  [data-c="showcase"] .showcase-path-text {    direction: ltr;    unicode-bidi: isolate;  }  [data-c="showcase"] .showcase-copy { color: var(--color-muted); }  [data-c="showcase"] .showcase-copy:hover { color: var(--color-ink); }  [data-c="showcase"] :is(.showcase-file, .showcase-check-icon, .showcase-copy-done, .showcase-copy-blocked, .showcase-expand, .showcase-expand-less) { display: none; }  [data-c="showcase"] .showcase-copy.is-done { color: var(--color-accent-text); }  [data-c="showcase"] .is-done :is(.showcase-copy-idle, .showcase-copy-icon) { display: none; }  [data-c="showcase"] .is-done .showcase-copy-done { display: inline; }  [data-c="showcase"] .is-done .showcase-check-icon {    display: block;    stroke-dasharray: 16;    animation: showcase-check 0.32s var(--ease-out) both;  }  [data-c="showcase"] .showcase-copy.is-blocked { color: var(--color-warning); }  [data-c="showcase"] .is-blocked .showcase-copy-idle { display: none; }  [data-c="showcase"] .is-blocked .showcase-copy-blocked { display: inline; }  [data-c="showcase"] .showcase-code {    --line-gutter: 3rem;    --hang: 2ch;    flex: 1;    max-height: 32rem;    margin: 0;    padding: 0.5rem 0 1.25rem;    overflow: auto;    color: var(--color-ink);    font-size: 0.8125rem;    line-height: 1.7;    tab-size: 2;    counter-reset: line;  }  [data-c="showcase"] .code-line {    position: relative;    display: block;    min-height: 1lh;    padding-right: 1.25rem;    padding-left: calc(var(--line-gutter) + var(--indent, 0ch) + var(--hang));    text-indent: calc(-1 * (var(--indent, 0ch) + var(--hang)));    white-space: pre-wrap;    overflow-wrap: anywhere;    counter-increment: line;  }  [data-c="showcase"] .code-line::before {    content: counter(line);    position: absolute;    left: 0;    width: calc(var(--line-gutter) - 1rem);    color: var(--code-gutter);    text-align: right;    text-indent: 0;  }  [data-c="showcase"] [data-indent="2"] { --indent: 2ch; }  [data-c="showcase"] [data-indent="4"] { --indent: 4ch; }  [data-c="showcase"] [data-indent="6"] { --indent: 6ch; }  [data-c="showcase"] [data-indent="8"] { --indent: 8ch; }  [data-c="showcase"] [data-indent="10"] { --indent: 10ch; }  [data-c="showcase"] [data-indent="12"] { --indent: 12ch; }  [data-c="showcase"] [data-indent="14"] { --indent: 14ch; }  [data-c="showcase"] [data-indent="16"] { --indent: 16ch; }  [data-c="showcase"] .code-line::highlight(code-keyword) { color: var(--code-keyword); }  [data-c="showcase"] .code-line::highlight(code-string) { color: var(--code-string); }  [data-c="showcase"] .code-line::highlight(code-number) { color: var(--code-number); }  [data-c="showcase"] .code-line::highlight(code-tag) { color: var(--code-tag); }  [data-c="showcase"] .code-line::highlight(code-attribute) { color: var(--code-attribute); }  [data-c="showcase"] .code-line::highlight(code-title) { color: var(--code-property); }  [data-c="showcase"] .code-line::highlight(code-comment) { color: var(--code-comment); }  [data-c="showcase"] .code-line::highlight(code-punctuation) { color: var(--code-punctuation); }  [data-c="showcase"] .code-line::highlight(code-directive) { color: var(--color-accent-text); }  [data-c="showcase"] .code-line::highlight(code-component) { color: var(--code-number); }  [data-c="showcase"] .is-expanded .showcase-expand-more { display: none; }  [data-c="showcase"] .is-expanded .showcase-expand-less { display: inline; }  [data-c="showcase"] .showcase-live {    border-top: 1px solid var(--color-line);    background: var(--color-ground) radial-gradient(var(--color-line) 1px, transparent 1px) -10px -10px / 20px 20px;  }  [data-c="showcase"] .showcase-dot[data-beat="a"] { animation: showcase-beat-a 0.7s var(--ease-out); }  [data-c="showcase"] .showcase-dot[data-beat="b"] { animation: showcase-beat-b 0.7s var(--ease-out); }  [data-c="showcase"] .showcase-stage {    display: grid;    flex: 1;    grid-template-columns: minmax(0, 1fr);    place-items: center;    min-height: 14rem;    padding: 2rem 1rem;    overflow-x: auto;  }  [data-c="showcase"] .showcase-stage > * { max-width: 100%; }  @keyframes showcase-check {    from { stroke-dashoffset: 16; }  }  @keyframes showcase-beat-a {    from { scale: 2.2; }  }  @keyframes showcase-beat-b {    from { scale: 2.2; }  }  @media (max-width: 47.99rem) {    [data-c="showcase"] .showcase-code { --line-gutter: 2.5rem; max-height: none; }    [data-c="showcase"] .is-long .showcase-expand { display: flex; }    [data-c="showcase"]:not(.is-expanded) .is-long .showcase-code {      max-height: 17rem;      overflow: hidden;      mask-image: linear-gradient(#000 calc(100% - 4rem), transparent);    }  }  @media (min-width: 40rem) {    [data-c="showcase"] .showcase-stage { padding: 2.5rem 1.5rem; }  }  @media (min-width: 64rem) {    [data-c="showcase"] .code-line { white-space: pre; }  }  @media (min-width: 80rem) {    [data-c="showcase"] { grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr); }    [data-c="showcase"] .showcase-live { border-top: 0; border-left: 1px solid var(--color-line); }    [data-c="showcase"]:not(:has(.showcase-stage [data-c="frame"])) .showcase-code {      flex: 1 1 0;      min-height: 20rem;      max-height: none;    }  }  [data-c="showcase"]:has(.showcase-stage [data-c="frame"]) { grid-template-columns: minmax(0, 1fr); }  [data-c="showcase"]:has(.showcase-stage [data-c="frame"]) .showcase-live { border-top: 1px solid var(--color-line); border-left: 0; }  [data-c="showcase"] .showcase-stage:has([data-c="frame"]) {    place-items: stretch;    min-height: 0;    padding: 0.75rem;  }  @media (prefers-reduced-motion: reduce) {    [data-c="showcase"] .is-done .showcase-check-icon,    [data-c="showcase"] .showcase-dot[data-beat] { animation: none; }  }</style>

Live result

highlight.js bundle size by import style
Import Raw Gzip
import hljs from 'highlight.js' index entry: all 193 languages 926.7 kB 303.4 kB
@lezer/highlight + javascript, html, css pure ESM, rejected: the JS grammar alone is 29.6 kB 161.5 kB 60.9 kB
highlight.js/lib/core + xml, javascript, css used on this site: on the server for every showcase, in the browser only via import() on the SEO page 40.8 kB 14.8 kB
Sizes of dist/client/assets/npm/highlight.js-*.js after pragma build. The tabs show the server-side tokenizer and the client-side painter.

Named imports: only what you use ships

valibot is pure ESM with one module per function, the best case for tree shaking. This form imports eight names and ships 1.35 kB gzip of valibot. The schema is a constant in the <script>; validation is a derived function, so {$status} reruns it on every keystroke without any wiring.

routes/examples/packages/_components/email-check/email-check.html

<script>  import { email, maxLength, nonEmpty, object, pipe, safeParse, string, trim } from 'valibot'  const signup = object({    email: pipe(string(), trim(), nonEmpty('Type an email.'), email('That is not an email address.'), maxLength(64, 'Keep it under 64 characters.')),  })  let address = 'ana@example'  let joined = ''  const validation = () => safeParse(signup, { email: address })  const valid = () => validation().success  const invalid = () => !valid()  const ariaInvalid = () => (valid() ? 'false' : 'true')  function status() {    const result = validation()    if (!result.success) return result.issues[0].message    return joined === result.output.email ? 'Joined as ' + joined : 'Looks good.'  }  function submit() {    const result = validation()    if (result.success) joined = result.output.email  }</script><form class="grid w-full max-w-sm gap-2.5 font-mono text-xs" notool @submit="submit" novalidate>  <label for="signup-email" class="text-muted">Work email</label>  <div class="flex gap-2">    <input id="signup-email" type="email" class="h-8 min-w-0 flex-1 border bg-surface px-3 text-sm text-ink" autocomplete="off" spellcheck="false" :model="$address" :aria-invalid="$ariaInvalid" aria-describedby="signup-email-status">    <button type="submit" class="btn btn-small" :disabled="$invalid">Join</button>  </div>  <p id="signup-email-status" class="min-h-5" role="status" .text-accent-text="$valid" .text-warning="$invalid">{$status}</p></form><style>  input { border-color: var(--color-line-strong); }  input[aria-invalid="true"] { border-color: var(--color-warning-500); }</style>

Live result

Type to validate. Messages come from the schema; the button stays disabled until it passes.

Subpath imports share one chunk

groupBy comes from the es-toolkit index and debounce from es-toolkit/function. Both end up in a single es-toolkit-*.js of 0.43 kB gzip. The same two helpers from lodash cost 6.49 kB, because CommonJS cannot be shaken.

The debounced function just assigns two let variables: a timer firing outside an action still renders, because state is a reactive Proxy. mount() returns a cleanup that cancels a pending call when the component leaves the page.

routes/examples/packages/_components/stock-filter/stock-filter.html

<script>  import { groupBy } from 'es-toolkit'  import { debounce } from 'es-toolkit/function'  const products = [    { name: 'Roasted coffee', category: 'drinks' },    { name: 'Green tea', category: 'drinks' },    { name: 'Oat milk', category: 'drinks' },    { name: 'Sourdough bread', category: 'bakery' },    { name: 'Butter croissant', category: 'bakery' },    { name: 'Brown sugar', category: 'pantry' },    { name: 'Black tea leaves', category: 'pantry' },  ]  let term = ''  let applied = ''  let keystrokes = 0  let runs = 0  const applyLater = debounce(() => {    applied = term.trim().toLowerCase()    runs += 1  }, 300)  function groups() {    const matching = products.filter(product => product.name.toLowerCase().includes(applied))    return Object.entries(groupBy(matching, product => product.category))      .map(([category, inCategory]) => ({ category, names: inCategory.map(product => product.name).join(', ') }))  }  function scheduleFilter() {    keystrokes += 1    applyLater()  }  function mount() {    return () => applyLater.cancel()  }</script><div class="grid w-full max-w-md gap-3">  <label class="grid gap-3 font-mono text-xs text-muted">    Filter products    <input type="search" class="h-9 border border-line-strong bg-surface px-3 text-sm text-ink" placeholder="tea, bread, oat..." autocomplete="off" :model="$term" @input="scheduleFilter">  </label>  <p class="flex justify-between font-mono text-xs tabular-nums text-faint"><span>{$keystrokes} keystrokes</span><span>{$runs} filter runs</span></p>  <ul class="divide-y divide-line border-y border-line text-sm">    <for group in $groups key=group.category>      <li class="grid grid-cols-4 gap-4 py-2.5">        <span class="font-mono text-xs leading-relaxed text-accent-text">{group.category}</span>        <span class="col-span-3 text-ink">{group.names}</span>      </li>    </for>    <empty>      <li class="py-2.5 text-faint">No product matches.</li>    </empty>  </ul></div>

Live result

Type quickly: keystrokes climb, filter runs only count once you pause for 300 ms.

CommonJS, loaded with import() after a click

dayjs is CommonJS, so the core and the relativeTime plugin ship whole: 3.69 kB gzip. When a package is only needed after an interaction, await import() it inside the action. The chunk is left out of the modulepreload list and the page size, and the first paint does not wait for it.

import('pkg') always brings the whole package, so keep it for code you need all of anyway. The default export of a CommonJS module arrives as default.

routes/examples/packages/_components/relative-time/relative-time.html

<script>  import { log } from 'pragma'  const releaseDates = [    { version: 'v0.3.0', date: '2026-11-02' },    { version: 'v0.2.0', date: '2026-08-14' },    { version: 'v0.1.0', date: '2025-12-01' },  ]  const statusByPhase = {    idle: 'dayjs is not loaded yet.',    loading: 'Fetching the chunk...',    failed: 'Could not load dayjs.',  }  let phase = 'idle'  let loadMs = 0  let agoByVersion = {}  const busy = () => phase === 'loading'  const buttonText = () => (phase === 'ready' ? 'Recompute' : 'Load dayjs')  const releases = () => releaseDates.map(release => ({ ...release, ago: agoByVersion[release.version] ?? '—' }))  const status = () => (phase === 'ready' ? 'dayjs arrived in ' + loadMs + ' ms, after first paint.' : statusByPhase[phase])  async function loadRelativeTimes() {    const startedAt = performance.now()    phase = 'loading'    try {      const [{ default: dayjs }, { default: relativeTime }] = await Promise.all([        import('dayjs'),        import('dayjs/plugin/relativeTime'),      ])      dayjs.extend(relativeTime)      agoByVersion = Object.fromEntries(releaseDates.map(release => [release.version, dayjs(release.date).fromNow()]))      loadMs = Math.round(performance.now() - startedAt)      phase = 'ready'    } catch (failure) {      log.warn('dayjs import failed', { 'exception.message': failure.message })      phase = 'failed'    }  }</script><div class="grid w-full max-w-md gap-4 font-mono text-xs">  <ul class="divide-y divide-line border-y border-line tabular-nums">    <for release in $releases key=release.version>      <li class="flex gap-3 py-2.5">        <span class="w-16 text-ink">{release.version}</span>        <span class="text-faint">{release.date}</span>        <span class="ml-auto text-accent-text">{release.ago}</span>      </li>    </for>  </ul>  <div class="flex flex-wrap items-center gap-x-4 gap-y-3">    <button type="button" class="btn btn-small" @click="loadRelativeTimes" :disabled="$busy">{$buttonText}</button>    <p class="text-faint" role="status">{$status}</p>  </div></div>

Live result

Open the network panel, then click: dayjs-*.js is requested only now.

What common packages cost

Gzip size of the /assets/npm/ file for each import, measured with pragma build on the packages test app in core/cli/xtask/packages/app. The runtime alone is 8.7 kB gzip per page, so a large package like chart.js belongs behind an import().

Gzip size per npm package import
Import Raw Gzip
es-toolkit groupBy + debounce, ESM 0.67 kB 0.43 kB
valibot object, pipe, string, email, safeParse, ESM 3.40 kB 1.35 kB
@date-fns/tz TZDate, ESM 4.90 kB 1.75 kB
dayjs core + relativeTime, CommonJS: ships whole 8.75 kB 3.69 kB
lodash groupBy + sumBy, CommonJS: ships whole 22.0 kB 6.49 kB
date-fns format, ESM (format pulls the locale code) 25.0 kB 6.69 kB
fuse.js Fuse class, one export 26.5 kB 9.21 kB
chart.js bar chart: 5 registered pieces 132.6 kB 46.0 kB

Prefer the platform first: Intl for dates, numbers and plurals, fetch, crypto.randomUUID(), structuredClone. Avoid moment, lodash, axios, uuid, nanoid and anything that builds HTML.

Packages that fail the check

The error points at the import in your file. UI frameworks are rejected because the runtime owns the DOM; Node built-ins only run in .server.js; remote URLs and unlisted packages have to be installed. This is real pragma check output.

~/my-app
pragma check
routes/err.js:1:27 error [js/import] package "react" is a UI framework; in pragma markup lives in .html and the runtime owns the DOM
 1 | import { useState } from 'react'
   |                           ^
routes/err.js:2:27 error [js/import] `groupByy` is not exported by es-toolkit
 2 | import { groupByy } from 'es-toolkit'
   |                           ^
routes/err.js:3:26 error [app/package] `node:fs/promises` is a Node module and doesn't run in the browser; use it in a .server.js
 3 | import { readFile } from 'node:fs/promises'
   |                          ^
routes/err.js:4:25 error [js/import] package "nanoid" is not in package.json dependencies; install with `npm i nanoid` or `bun add nanoid`
 4 | import { nanoid } from 'nanoid'
   |                         ^
4 error(s), 0 warning(s)
pragma check
routes/err.js:1:24 error [js/import] remote import `https://esm.sh/date-fns` is not allowed; install the package (npm i, bun add) or copy the code into the project
 1 | import { format } from 'https://esm.sh/date-fns'
   |                        ^
1 error(s), 0 warning(s)
pragma check
routes/err.js:3:18 error [js/import] package import `dayjs` must use quotes, not a template literal
 3 |     await import(`dayjs`)
   |                  ^
routes/err.js:5:18 error [js/import] `import()` needs a quoted path or package name (`import('./chart.js')`, `import('dayjs')`); the build cannot follow a computed specifier
 5 |     await import(name)
   |                  ^
2 error(s), 0 warning(s)

Also rejected, with app/package: TypeScript, JSX, .vue and .svelte files, and packages that import CSS or other assets. The same list covers Preact, Vue, Svelte, Solid, lit, jQuery and Alpine. A misspelled name is caught at check time, not in the browser, and so is an import() whose specifier is a variable.

Packages on the server

A .server.js file can import any package from package.json plus Node built-ins (node:fs, node:crypto) without listing them. Server code is not bundled: dist/server/ keeps your imports and Node resolves node_modules by walking up from it. A built-in name listed in package.json, such as the buffer polyfill, is bundled for the client like any other package.