fetch.macro
Allows you to build fetcher function by URL at compile-time.
Usage
Simply install and configure babel-plugin-macros
and then use fetch.macro
.
Vite
To be able to use these macros in your Vite project, you only need install vite-plugin-babel-macros
and add some configuration in vite.config.js
. And it just work.
$ npm i -D vite-plugin-babel-macros
import MacrosPlugin from "vite-plugin-babel-macros";
export default {
// ...
plugins: [
// ...
MacrosPlugin(),
],
};
Example
Basic
Given the following Input
:
import f from "fetch.macro";
const fetchByUrl = f("/api/v1/ping");
Babel will produce the following Output
:
const fetchByUrl = (opts) => fetch("/api/v1/ping", opts);
It also works as a tagged template
literal:
import f from "fetch.macro";
const fetchByUrl = f`/api/v1/ping`;
That will produce the same output as the function version.
Nested
Given the following Input
:
import f from "fetch.macro";
const fetchProject = f`/api/v1/user/:id/project/:projectId/:others`;
Babel will produce the following Output
:
const fetchProject = ({ id, projectId, others, ...opts }) =>
fetch(`/api/v1/user/${id}/project/${projectId}/${others}`, opts);
Contributors
RiN |
Ryan Aunur Rassyid |