Skip to content

Commit

Permalink
feat(sfc): allow sfcs to recursively self-reference in template via n…
Browse files Browse the repository at this point in the history
…ame inferred from filename

e.g. A file named `FooBar.vue` can refer to itself as `<FooBar/>`. This gets rid of the need for the `name` option.
  • Loading branch information
yyx990803 committed Nov 30, 2020
1 parent 29d256c commit 67d1aac
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ describe('compiler: element transform', () => {
expect(root.components).toContain(`Foo`)
})

test('resolve implcitly self-referencing component', () => {
const { root } = parseWithElementTransform(`<Example/>`, {
filename: `/foo/bar/Example.vue?vue&type=template`
})
expect(root.helpers).toContain(RESOLVE_COMPONENT)
expect(root.components).toContain(`_self`)
})

test('static props', () => {
const { node } = parseWithElementTransform(`<div id="foo" class="bar" />`)
expect(node).toMatchObject({
Expand Down
11 changes: 6 additions & 5 deletions packages/compiler-core/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ interface SharedTransformCodegenOptions {
* Indicates that transforms and codegen should try to output valid TS code
*/
isTS?: boolean
/**
* Filename for source map generation.
* Also used for self-recursive reference in templates
* @default 'template.vue.html'
*/
filename?: string
}

export interface TransformOptions extends SharedTransformCodegenOptions {
Expand Down Expand Up @@ -218,11 +224,6 @@ export interface CodegenOptions extends SharedTransformCodegenOptions {
* @default false
*/
sourceMap?: boolean
/**
* Filename for source map generation.
* @default 'template.vue.html'
*/
filename?: string
/**
* SFC scoped styles ID
*/
Expand Down
11 changes: 9 additions & 2 deletions packages/compiler-core/src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ import {
NOOP,
PatchFlags,
PatchFlagNames,
EMPTY_OBJ
EMPTY_OBJ,
capitalize,
camelize
} from '@vue/shared'
import { defaultOnError } from './errors'
import {
Expand Down Expand Up @@ -79,7 +81,9 @@ export interface ImportItem {
path: string
}

export interface TransformContext extends Required<TransformOptions> {
export interface TransformContext
extends Required<Omit<TransformOptions, 'filename'>> {
selfName: string | null
root: RootNode
helpers: Set<symbol>
components: Set<string>
Expand Down Expand Up @@ -112,6 +116,7 @@ export interface TransformContext extends Required<TransformOptions> {
export function createTransformContext(
root: RootNode,
{
filename = '',
prefixIdentifiers = false,
hoistStatic = false,
cacheHandlers = false,
Expand All @@ -130,8 +135,10 @@ export function createTransformContext(
onError = defaultOnError
}: TransformOptions
): TransformContext {
const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/)
const context: TransformContext = {
// options
selfName: nameMatch && capitalize(camelize(nameMatch[1])),
prefixIdentifiers,
hoistStatic,
cacheHandlers,
Expand Down
11 changes: 10 additions & 1 deletion packages/compiler-core/src/transforms/transformElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,16 @@ export function resolveComponentType(
}
}

// 4. user component (resolve)
// 4. Self referencing component (inferred from filename)
if (!__BROWSER__ && context.selfName) {
if (capitalize(camelize(tag)) === context.selfName) {
context.helper(RESOLVE_COMPONENT)
context.components.add(`_self`)
return toValidAssetId(`_self`, `component`)
}
}

// 5. user component (resolve)
context.helper(RESOLVE_COMPONENT)
context.components.add(tag)
return toValidAssetId(tag, `component`)
Expand Down
25 changes: 12 additions & 13 deletions packages/compiler-sfc/src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export interface SFCBlock {

export interface SFCTemplateBlock extends SFCBlock {
type: 'template'
functional?: boolean
ast: ElementNode
}

export interface SFCScriptBlock extends SFCBlock {
Expand Down Expand Up @@ -79,7 +79,7 @@ export function parse(
source: string,
{
sourceMap = true,
filename = 'component.vue',
filename = 'anonymous.vue',
sourceRoot = '',
pad = false,
compiler = CompilerDOM
Expand Down Expand Up @@ -143,39 +143,40 @@ export function parse(
switch (node.tag) {
case 'template':
if (!descriptor.template) {
descriptor.template = createBlock(
const templateBlock = (descriptor.template = createBlock(
node,
source,
false
) as SFCTemplateBlock
) as SFCTemplateBlock)
templateBlock.ast = node
} else {
errors.push(createDuplicateBlockError(node))
}
break
case 'script':
const block = createBlock(node, source, pad) as SFCScriptBlock
const isSetup = !!block.attrs.setup
const scriptBlock = createBlock(node, source, pad) as SFCScriptBlock
const isSetup = !!scriptBlock.attrs.setup
if (isSetup && !descriptor.scriptSetup) {
descriptor.scriptSetup = block
descriptor.scriptSetup = scriptBlock
break
}
if (!isSetup && !descriptor.script) {
descriptor.script = block
descriptor.script = scriptBlock
break
}
errors.push(createDuplicateBlockError(node, isSetup))
break
case 'style':
const style = createBlock(node, source, pad) as SFCStyleBlock
if (style.attrs.vars) {
const styleBlock = createBlock(node, source, pad) as SFCStyleBlock
if (styleBlock.attrs.vars) {
errors.push(
new SyntaxError(
`<style vars> has been replaced by a new proposal: ` +
`https://github.com/vuejs/rfcs/pull/231`
)
)
}
descriptor.styles.push(style)
descriptor.styles.push(styleBlock)
break
default:
descriptor.customBlocks.push(createBlock(node, source, pad))
Expand Down Expand Up @@ -290,8 +291,6 @@ function createBlock(
} else if (p.name === 'module') {
;(block as SFCStyleBlock).module = attrs[p.name]
}
} else if (type === 'template' && p.name === 'functional') {
;(block as SFCTemplateBlock).functional = true
} else if (type === 'script' && p.name === 'setup') {
;(block as SFCScriptBlock).setup = attrs.setup
}
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime-core/src/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ export function formatComponentName(
? Component.displayName || Component.name
: Component.name
if (!name && Component.__file) {
const match = Component.__file.match(/([^/\\]+)\.vue$/)
const match = Component.__file.match(/([^/\\]+)\.\w+$/)
if (match) {
name = match[1]
}
Expand Down
6 changes: 6 additions & 0 deletions packages/runtime-core/src/helpers/resolveAssets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ function resolveAsset(

// self name has highest priority
if (type === COMPONENTS) {
// special self referencing call generated by compiler
// inferred from SFC filename
if (name === `_self`) {
return Component
}

const selfName =
(Component as FunctionalComponent).displayName || Component.name
if (
Expand Down
4 changes: 2 additions & 2 deletions packages/template-explorer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ window.init = () => {
const compileFn = ssrMode.value ? ssrCompile : compile
const start = performance.now()
const { code, ast, map } = compileFn(source, {
filename: 'template.vue',
filename: 'ExampleTemplate.vue',
...compilerOptions,
sourceMap: true,
onError: err => {
Expand Down Expand Up @@ -150,7 +150,7 @@ window.init = () => {
clearEditorDecos()
if (lastSuccessfulMap) {
const pos = lastSuccessfulMap.generatedPositionFor({
source: 'template.vue',
source: 'ExampleTemplate.vue',
line: e.position.lineNumber,
column: e.position.column - 1
})
Expand Down

0 comments on commit 67d1aac

Please sign in to comment.