https://github.com/neplextech/directive-to-hof
Transform directives into a higher order function
https://github.com/neplextech/directive-to-hof
Last synced: 12 months ago
JSON representation
Transform directives into a higher order function
- Host: GitHub
- URL: https://github.com/neplextech/directive-to-hof
- Owner: neplextech
- License: mit
- Created: 2025-04-18T16:54:06.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2025-04-22T14:10:11.000Z (about 1 year ago)
- Last Synced: 2025-06-11T10:09:56.443Z (about 1 year ago)
- Language: TypeScript
- Homepage: https://npm.im/directive-to-hof
- Size: 18.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README



# directive-to-hof
Transform directives into a higher order function.
# Installation
```sh
$ npm i directive-to-hof
```
# Features
- **No runtime magic**: The directive is transformed into a higher order function call.
- **Compiles like a boss**: The directive is transformed into a higher order function call at build time.
- **Pragmas are code too**: Treat directives as code. This means you can use them in any context where you would use a function call.
# Usage
## Vite/Rollup Plugin
```ts
import { vite as viteDirective } from 'directive-to-hof';
export default defineConfig({
plugins: [
viteDirective({
directive: 'use once', // the directive to look for
importPath: './use-once-function.js', // lib name/path to import the higher order function from
importName: 'useOnce', // the higher order function name to import
asyncOnly: false, // only allow async functions
}),
],
});
```
> import `rollup` for rollup
## esbuild
```ts
import { esbuild } from 'directive-to-hof';
// plugins array
plugins: [
esbuild({
directive: 'use once', // the directive to look for
importPath: './use-once-function.js', // lib name/path to import the higher order function from
importName: 'useOnce', // the higher order function name to import
asyncOnly: false, // only allow async functions
}),
];
```
## API
```js
// use-once-function.js
export function useOnce(fn) {
let result;
return (...args) => {
if (result !== undefined) return result;
return (result = fn(...args));
};
}
```
```ts
import { createDirectiveTransformer } from 'directive-to-hof';
const transformer = createDirectiveTransformer({
directive: 'use once', // the directive to look for
importPath: './use-once-function.js', // lib name/path to import the higher order function from
importName: 'useOnce', // the higher order function name to import
asyncOnly: false, // only allow async functions
});
const code = `
let count = 0;
function increment() {
'use once';
return ++count;
}
`;
const { contents } = await transformer(code, { path: import.meta.filename });
console.log(contents);
/*
import { useOnce } from "./use-once-function.js"
let count = 0;
const increment = useOnce(() => {
return ++count;
});
*/
```