Skip to content

Commit

Permalink
feat(compiler-core): add filename to TransformContext
Browse files Browse the repository at this point in the history
When using `nodeTransform`, I have found myself needing the filename to do filesystem operations, which well cannot be done without the filename of the current component in the context passed to the function
  • Loading branch information
Tofandel committed Aug 10, 2023
1 parent 3be4e3c commit 6ea9062
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
19 changes: 19 additions & 0 deletions packages/compiler-core/__tests__/transform.spec.ts
Expand Up @@ -200,6 +200,25 @@ describe('compiler: transform', () => {
expect((ast as any).children[0].props[0].exp.content).toBe(`_hoisted_1`)
expect((ast as any).children[1].props[0].exp.content).toBe(`_hoisted_2`)
})

test('context.filename', () => {
const ast = baseParse(`<div />`)

const calls: any[] = []
const plugin: NodeTransform = (node, context) => {
calls.push({ ...context })
}

transform(ast, {
filename: '/the/filename.vue',
nodeTransforms: [plugin]
})

expect(calls.length).toBe(1)
expect(calls[0]).toMatchObject({
filename: '/the/filename.vue'
})
})

test('onError option', () => {
const ast = baseParse(`<div/>`)
Expand Down
3 changes: 2 additions & 1 deletion packages/compiler-core/src/transform.ts
Expand Up @@ -84,7 +84,7 @@ export interface ImportItem {

export interface TransformContext
extends Required<
Omit<TransformOptions, 'filename' | keyof CompilerCompatOptions>
Omit<TransformOptions, keyof CompilerCompatOptions>
>,
CompilerCompatOptions {
selfName: string | null
Expand Down Expand Up @@ -152,6 +152,7 @@ export function createTransformContext(
const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/)
const context: TransformContext = {
// options
filename,
selfName: nameMatch && capitalize(camelize(nameMatch[1])),
prefixIdentifiers,
hoistStatic,
Expand Down

0 comments on commit 6ea9062

Please sign in to comment.