Skip to content

Commit

Permalink
fix: helpful error message during dev when no active twind instance i…
Browse files Browse the repository at this point in the history
…s found
  • Loading branch information
sastan committed Nov 3, 2022
1 parent 6d9d372 commit fe891f9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-chicken-look.md
@@ -0,0 +1,5 @@
---
'twind': patch
---

helpful error message during dev when no active twind instance is found
29 changes: 23 additions & 6 deletions packages/twind/src/runtime.ts
Expand Up @@ -12,6 +12,7 @@ import { twind } from './twind'
import { observe } from './observe'
import { getSheet } from './sheets'
import { noop } from './utils'
import { DEV } from 'distilt/env'

export function auto(setup: () => void): () => void {
// If we run in the browser we call setup at latest when the body is inserted
Expand Down Expand Up @@ -42,33 +43,49 @@ export function auto(setup: () => void): () => void {
return noop
}

let active: Twind

function assertActive() {
if (DEV && !active) {
throw new Error(
`No active twind instance found. Make sure to call setup or install before accessing tw.`,
)
}
}

/**
* A proxy to the currently active Twind instance.
*/

export const tw = /* #__PURE__ */ new Proxy(
// just exposing the active as tw should work with most bundlers
// as ES module export can be re-assigned BUT some bundlers to not honor this
// -> using a delegation proxy here
noop as unknown as Twind<any, any>,
{
apply(_target, _thisArg, args) {
if (DEV) assertActive()

return active(args[0])
},
get(target, property) {
const value = (active || target)[property as keyof Twind]
get(_target, property) {
if (DEV) assertActive()

const value = active[property as keyof Twind]

if (typeof value === 'function') {
return value.bind(active)
return function () {
if (DEV) assertActive()

// eslint-disable-next-line prefer-rest-params
return value.apply(active, arguments)
}
}

return value
},
},
)

let active: Twind

export type SheetFactory<SheetTarget = unknown> = () => Sheet<SheetTarget>

/**
Expand Down

0 comments on commit fe891f9

Please sign in to comment.