Skip to content

Commit

Permalink
Merge pull request #11 from pcattori/unreplaced-macros-throw
Browse files Browse the repository at this point in the history
feat: unreplaced macros throw an error
  • Loading branch information
pcattori authored Jan 8, 2024
2 parents 7bb3989 + c14f801 commit 6fa1f68
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 15 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default defineConfig({
### `server$`

```ts
declare const server$: <T>(x: T) => T | undefined
declare const server$: <T>(_: T) => T | undefined
```
Marks an expression as server-only and replaces it with `undefined` on the client.
Expand All @@ -54,7 +54,7 @@ export const message = undefined
### `client$`

```ts
declare const client$: <T>(x: T) => T | undefined
declare const client$: <T>(_: T) => T | undefined
```
Marks an expression as client-only and replaces it with `undefined` on the server.
Expand Down
14 changes: 1 addition & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,7 @@ import type { Plugin } from "vite"
import { name as pkgName } from "../package.json"
import { transform } from "./transform"

const maybe = <T>(x: T): T | undefined => x

/**
* On the server, returns the value passed in.
* On the client, returns `undefined`.
*/
export const server$ = maybe

/**
* On the client, returns the value passed in.
* On the server, returns `undefined`.
*/
export const client$ = maybe
export { server$, client$ } from "./macro"

export default (): Plugin => {
return {
Expand Down
8 changes: 8 additions & 0 deletions src/macro.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { expect, test } from "vitest"

import { server$, client$ } from "./macro"

test("unreplaced macro throws error", () => {
expect(() => server$("hello")).toThrowError(/unreplaced macro/)
expect(() => client$("world")).toThrowError(/unreplaced macro/)
})
24 changes: 24 additions & 0 deletions src/macro.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { name as pkgName } from "../package.json"

const maybe = <T>(_: T): T | undefined => {
throw Error(
[
`${pkgName}: unreplaced macro`,
"",
`Did you forget to add the '${pkgName}' plugin to your Vite config?`,
"👉 https://github.com/pcattori/vite-env-only?tab=readme-ov-file#installation",
].join("\n"),
)
}

/**
* On the server, replaced with the value passed in.
* On the client, replaced with `undefined`.
*/
export const server$ = maybe

/**
* On the client, replaced with the value passed in.
* On the server, replaced with `undefined`.
*/
export const client$ = maybe

0 comments on commit 6fa1f68

Please sign in to comment.