0.1.1 • Published 3 years ago
@ulab/create-vite-macro-plugin v0.1.1
@ulab/create-vite-macro-plugin
Create macro plugins for vite.
Getting Started
Install:
$ npm install -D @ulab/create-vite-macro-plugin
# or
# yarn add -D @ulab/create-vite-macro-plugin
Add to your vite.config.ts
:
import { defineConfig } from 'vite'
import { createMacroPlugin } from '@ulab/create-vite-macro-plugin'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [createMacroPlugin({ macros: [] })],
})
Add to your src/vite-env.d.ts
:
/// <reference types="@ulab/create-vite-macro-plugin/client" />
Overview
First register macros in form like createMacroPlugin({ macros: [macroA, macroB] })
or
createMacroPlugin({ macros: {namespace1: [macroA, macroB]} })
.
Then you can import macros from namespace (defaults to @macros
) and call them as normal function.
Since you have added @ulab/create-vite-macro-plugin/client
in src/vite-env.d.ts
, you
can get placeholder types of macros.
Type declarations will be created automatically when vite dev server starts.
Example
// macros/echo.ts
import { defineMacro } from '@ulab/create-vite-macro-plugin'
export default defineMacro(
// placeholder type, can be an array of string
'(msg: string, repeat?: number): void',
// the name of the macro handler is also the name of macro
function echo({ path, args }, { template, types }) {
if (args.length === 0) throw new Error('empty arguments is invalid')
const firstArg = args[0]
if (!types.isStringLiteral(firstArg))
throw new Error('please use literal string as message')
let repeat = 5
if (args.length > 1) {
const secondArg = args[1]
if (!types.isNumericLiteral(secondArg))
throw new Error('please use literal number as repeat')
repeat = secondArg.value
}
path.replaceWith(
template.statement.ast`console.log("${Array.from(
{ length: repeat },
() => firstArg.value
).join(' ')}")`
)
}
)
// vite.config.ts
export default defineConfig({
plugins: [
createMacroPlugin({
macros: {
// namespace: array of macros
'@echo': [EchoMacro],
},
}),
],
})
// in your project
import { echo } from '@echo'
echo('yeah', 3)
// It will be expanded into:
// console.log('yeah yeah yeah')
Configuration
export type MacroPluginOption = (
| {
macros: Macro[]
// default to '@macros'
namespace?: string
// type definitions, will be written to d.ts
typeDefinitions?: string
}
| {
macros: { [namespace: string]: Macro[] }
typeDefinitions: { [namespace: string]: string }
}
) & {
// name of plugin, default to 'macro-plugin'
name?: string
// path of the automatically generated type declaration file,
// default to '$rootDirOfThisPlugin/client.d.ts'
dtsPath?: string
// max recursion for applying macros,
// default to 5
maxRecursion?: number
// babel plugins to be applied during parsing
parserPlugins?: ParserPlugin[]
}
License
MIT License © 2021 unbyte