Skip to content

neplextech/directive-to-hof

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

"no runtime magic" "compiles like a boss" "pragmas are code too"

directive-to-hof

Transform directives into a higher order function.

Installation

$ 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

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

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

// use-once-function.js
export function useOnce(fn) {
  let result;

  return (...args) => {
    if (result !== undefined) return result;
    return (result = fn(...args));
  };
}
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;
});
*/

About

Transform directives into a higher order function

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published