Skip to content

Commit

Permalink
feat: add macro context
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Aug 29, 2023
1 parent 9d1f91e commit 7db57b8
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { MagicString, generateTransform } from 'magic-string-ast'
import { type ImportAttribute, type Node } from '@babel/types'
import { type ViteNodeRunner } from 'vite-node/client'

export * from './options'
export interface MacroContext {
id: string
}

interface MacroBase {
node: Node
id: string[]
Expand Down Expand Up @@ -140,7 +145,10 @@ export async function transformMacros(

let ret: any
if (macro.type === 'call') {
ret = exported(...macro.args)
const ctx: MacroContext = {
id,
}
ret = (exported as Function).apply(ctx, macro.args)
} else {
ret = exported
}
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { installSourcemapsSupport } from 'vite-node/source-map'
import { type Options, resolveOptions } from './core/options'
import { transformMacros } from './core'

export type { Options, MacroContext } from './core'

export default createUnplugin<Options | undefined, false>((rawOptions = {}) => {
const options = resolveOptions(rawOptions)
const filter = createFilter(options.include, options.exclude)
Expand Down
5 changes: 5 additions & 0 deletions tests/__snapshots__/fixtures.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ const { bar = 1 } = {};
"
`;

exports[`fixture > tests/fixtures/ctx.js 1`] = `
"\\"ctx.js\\" === 'ctx.js';
"
`;

exports[`fixture > tests/fixtures/dedent.js 1`] = `
"const msg = \\"if (true) {\\\\n const a = 'b'\\\\n}\\";
"
Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/ctx.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { getCtx } from './macros/ctx' assert { type: 'macro' }

getCtx() === 'ctx.js'
6 changes: 6 additions & 0 deletions tests/fixtures/macros/ctx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { MacroContext } from '../../../src'
import path from 'path'

export function getCtx(this: MacroContext) {
return path.basename(this.id)
}
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"compilerOptions": {
"target": "es2021",
"target": "esnext",
"module": "esnext",
"lib": ["es2021"],
"lib": ["es2022"],
"strict": true,
"esModuleInterop": true,
"moduleResolution": "bundler",
Expand Down

0 comments on commit 7db57b8

Please sign in to comment.