Skip to content

feat(compiler-sfc): introduce defineRender macro #9400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: minor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`defineRender() > JSX Element 1`] = `
"import { defineComponent as _defineComponent } from 'vue'

export default /*#__PURE__*/_defineComponent({
setup(__props, { expose: __expose }) {
__expose();



return () => <div />
}

})"
`;

exports[`defineRender() > empty argument 1`] = `
"const foo = 'bar'

export default {
setup(__props, { expose: __expose }) {
__expose();



return { foo }
}

}"
`;

exports[`defineRender() > function 1`] = `
"import { defineComponent as _defineComponent } from 'vue'

export default /*#__PURE__*/_defineComponent({
setup(__props, { expose: __expose }) {
__expose();



return () => <div />
}

})"
`;

exports[`defineRender() > identifier 1`] = `
"import { defineComponent as _defineComponent } from 'vue'
import { renderFn } from './ctx'

export default /*#__PURE__*/_defineComponent({
setup(__props, { expose: __expose }) {
__expose();



return renderFn
}

})"
`;
79 changes: 79 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript/defineRender.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { assertCode, compileSFCScript as compile } from '../utils'

describe('defineRender()', () => {
test('JSX Element', () => {
const { content } = compile(
`
<script setup lang="tsx">
defineRender(<div />)
</script>
`,
{ defineRender: true },
)
assertCode(content)
expect(content).toMatch(`return () => <div />`)
expect(content).not.toMatch('defineRender')
})

test('function', () => {
const { content } = compile(
`
<script setup lang="tsx">
defineRender(() => <div />)
</script>
`,
{ defineRender: true },
)
assertCode(content)
expect(content).toMatch(`return () => <div />`)
expect(content).not.toMatch('defineRender')
})

test('identifier', () => {
const { content } = compile(
`
<script setup lang="ts">
import { renderFn } from './ctx'
defineRender(renderFn)
</script>
`,
{ defineRender: true },
)
assertCode(content)
expect(content).toMatch(`return renderFn`)
expect(content).not.toMatch('defineRender')
})

test('empty argument', () => {
const { content } = compile(
`
<script setup>
const foo = 'bar'
defineRender()
</script>
`,
{ defineRender: true },
)
assertCode(content)
expect(content).toMatch(`return { foo }`)
expect(content).not.toMatch('defineRender')
})

describe('errors', () => {
test('w/ <template>', () => {
expect(() =>
compile(
`
<script setup lang="tsx">
defineRender(<div />)
</script>
<template>
<span>hello</span>
</template>
`,
{ defineRender: true },
),
).toThrow(`defineRender() cannot be used with <template>.`)
})
})
})
1 change: 1 addition & 0 deletions packages/compiler-sfc/__tests__/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function assertCode(code: string) {
plugins: [
'typescript',
['importAttributes', { deprecatedAssertSyntax: true }],
'jsx',
],
})
} catch (e: any) {
Expand Down
137 changes: 76 additions & 61 deletions packages/compiler-sfc/src/compileScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { getImportedName, isCallOf, isLiteralNode } from './script/utils'
import { analyzeScriptBindings } from './script/analyzeScriptBindings'
import { isImportUsed } from './script/importUsageCheck'
import { processAwait } from './script/topLevelAwait'
import { DEFINE_RENDER, processDefineRender } from './script/defineRender'

export interface SFCScriptCompileOptions {
/**
Expand Down Expand Up @@ -105,6 +106,11 @@ export interface SFCScriptCompileOptions {
* @default true
*/
hoistStatic?: boolean
/**
* (**Experimental**) Enable macro `defineRender`
* @default false
*/
defineRender?: boolean
/**
* (**Experimental**) Enable reactive destructure for `defineProps`
* @default false
Expand Down Expand Up @@ -491,7 +497,8 @@ export function compileScript(
processDefineProps(ctx, expr) ||
processDefineEmits(ctx, expr) ||
processDefineOptions(ctx, expr) ||
processDefineSlots(ctx, expr)
processDefineSlots(ctx, expr) ||
processDefineRender(ctx, expr)
) {
ctx.s.remove(node.start! + startOffset, node.end! + startOffset)
} else if (processDefineExpose(ctx, expr)) {
Expand Down Expand Up @@ -529,7 +536,8 @@ export function compileScript(
!isDefineProps && processDefineEmits(ctx, init, decl.id)
!isDefineEmits &&
(processDefineSlots(ctx, init, decl.id) ||
processDefineModel(ctx, init, decl.id))
processDefineModel(ctx, init, decl.id) ||
processDefineRender(ctx, init))

if (
isDefineProps &&
Expand Down Expand Up @@ -797,8 +805,22 @@ export function compileScript(
}

// 9. generate return statement
let returned
if (
let returned = ''
if (ctx.renderFunction) {
if (sfc.template) {
ctx.error(
`${DEFINE_RENDER}() cannot be used with <template>.`,
ctx.renderFunction,
)
}
if (ctx.renderFunction.type === 'JSXElement') {
returned = '() => '
}
returned += scriptSetup.content.slice(
ctx.renderFunction.start!,
ctx.renderFunction.end!,
)
} else if (
!options.inlineTemplate ||
(!sfc.template && ctx.hasDefaultExportRender)
) {
Expand Down Expand Up @@ -837,66 +859,59 @@ export function compileScript(
}
}
returned = returned.replace(/, $/, '') + ` }`
} else {
} else if (sfc.template && !sfc.template.src) {
// inline mode
if (sfc.template && !sfc.template.src) {
if (options.templateOptions && options.templateOptions.ssr) {
hasInlinedSsrRenderFn = true
}
// inline render function mode - we are going to compile the template and
// inline it right here
const { code, ast, preamble, tips, errors } = compileTemplate({
filename,
ast: sfc.template.ast,
source: sfc.template.content,
inMap: sfc.template.map,
...options.templateOptions,
id: scopeId,
scoped: sfc.styles.some(s => s.scoped),
isProd: options.isProd,
ssrCssVars: sfc.cssVars,
compilerOptions: {
...(options.templateOptions &&
options.templateOptions.compilerOptions),
inline: true,
isTS: ctx.isTS,
bindingMetadata: ctx.bindingMetadata,
},
})
if (tips.length) {
tips.forEach(warnOnce)
}
const err = errors[0]
if (typeof err === 'string') {
throw new Error(err)
} else if (err) {
if (err.loc) {
err.message +=
`\n\n` +
sfc.filename +
'\n' +
generateCodeFrame(
source,
err.loc.start.offset,
err.loc.end.offset,
) +
`\n`
}
throw err
}
if (preamble) {
ctx.s.prepend(preamble)
}
// avoid duplicated unref import
// as this may get injected by the render function preamble OR the
// css vars codegen
if (ast && ast.helpers.has(UNREF)) {
ctx.helperImports.delete('unref')
if (options.templateOptions && options.templateOptions.ssr) {
hasInlinedSsrRenderFn = true
}
// inline render function mode - we are going to compile the template and
// inline it right here
const { code, ast, preamble, tips, errors } = compileTemplate({
filename,
ast: sfc.template.ast,
source: sfc.template.content,
inMap: sfc.template.map,
...options.templateOptions,
id: scopeId,
scoped: sfc.styles.some(s => s.scoped),
isProd: options.isProd,
ssrCssVars: sfc.cssVars,
compilerOptions: {
...(options.templateOptions && options.templateOptions.compilerOptions),
inline: true,
isTS: ctx.isTS,
bindingMetadata: ctx.bindingMetadata,
},
})
if (tips.length) {
tips.forEach(warnOnce)
}
const err = errors[0]
if (typeof err === 'string') {
throw new Error(err)
} else if (err) {
if (err.loc) {
err.message +=
`\n\n` +
sfc.filename +
'\n' +
generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
`\n`
}
returned = code
} else {
returned = `() => {}`
throw err
}
if (preamble) {
ctx.s.prepend(preamble)
}
// avoid duplicated unref import
// as this may get injected by the render function preamble OR the
// css vars codegen
if (ast && ast.helpers.has(UNREF)) {
ctx.helperImports.delete('unref')
}
returned = code
} else {
returned = `() => {}`
}

if (!options.inlineTemplate && !__TEST__) {
Expand Down
4 changes: 4 additions & 0 deletions packages/compiler-sfc/src/script/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export class ScriptCompileContext {
hasDefaultExportRender = false
hasDefineOptionsCall = false
hasDefineSlotsCall = false
hasDefineRenderCall = false
hasDefineModelCall = false

// defineProps
Expand All @@ -59,6 +60,9 @@ export class ScriptCompileContext {
// defineOptions
optionsRuntimeDecl: Node | undefined

// defineRender
renderFunction?: Node

// codegen
bindingMetadata: BindingMetadata = {}
helperImports: Set<string> = new Set()
Expand Down
34 changes: 34 additions & 0 deletions packages/compiler-sfc/src/script/defineRender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Node } from '@babel/types'
import { isCallOf } from './utils'
import type { ScriptCompileContext } from './context'
import { warnOnce } from '../warn'

export const DEFINE_RENDER = 'defineRender'

export function processDefineRender(
ctx: ScriptCompileContext,
node: Node,
): boolean {
if (!isCallOf(node, DEFINE_RENDER)) {
return false
}

if (!ctx.options.defineRender) {
warnOnce(
`${DEFINE_RENDER}() is an experimental feature and disabled by default.\n` +
`To enable it, follow the RFC at https://github.com/vuejs/rfcs/discussions/585.`,
)
return false
}

if (ctx.hasDefineRenderCall) {
ctx.error(`duplicate ${DEFINE_RENDER}() call`, node)
}

ctx.hasDefineRenderCall = true
if (node.arguments.length > 0) {
ctx.renderFunction = node.arguments[0]
}

return true
}
Loading
Loading