Skip to content
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

feat(vue-template)!: auto unwrap refs #72

Merged
merged 1 commit into from
Jun 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 1 addition & 2 deletions playground/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<script setup lang="ts">
const count = ref(1)
const doubled = useDoubled(count)

function inc () {
count.value += 1
Expand All @@ -9,7 +8,7 @@ function inc () {

<template>
<div>
<h1>{{ count }} x {{ multiplier }} = {{ doubled }}</h1>
<h1>{{ count }} x {{ multiplier }} = {{ count * multiplier }}</h1>
<button @click="inc">
Inc
</button>
Expand Down
21 changes: 16 additions & 5 deletions src/addons/vue-template.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Import, Addon } from '../types'
import { toImports, toTypeDeclrationItems } from '../utils'
import { toImports } from '../utils'

const contextRE = /\b_ctx\.([\w_]+)\b/g
const UNREF_KEY = '_unimport_unref_'

export const vueTemplateAddon = (): Addon => ({
transform (s) {
Expand All @@ -22,8 +23,8 @@ export const vueTemplateAddon = (): Addon => ({
const start = match.index!
const end = start + match[0].length

const tempName = '__unimport_' + name
s.overwrite(start, end, tempName)
const tempName = `_unimport_${name}`
s.overwrite(start, end, `${UNREF_KEY}(${tempName})`)
if (!targets.find(i => i.as === tempName)) {
targets.push({
...item,
Expand All @@ -33,17 +34,27 @@ export const vueTemplateAddon = (): Addon => ({
}

if (targets.length) {
targets.push({
name: 'unref',
from: 'vue',
as: UNREF_KEY
})
s.prepend(toImports(targets))
}

return s
},
decleration (dts, options) {
const items = toTypeDeclrationItems(this.imports, options)
.map(i => i.replace('const ', ''))
const items = this.imports
.map((i) => {
const from = options?.resolvePath?.(i) || i.from
return `readonly ${i.as}: UnwrapRef<typeof import('${from}')${i.name !== '*' ? `['${i.name}']` : ''}>`
})
.sort()
return dts +
`
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface ComponentCustomProperties {
${items.map(i => ' ' + i).join('\n')}
Expand Down
79 changes: 57 additions & 22 deletions test/vue-template.test.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,85 @@
import { describe, expect, test } from 'vitest'
import { compileTemplate } from 'vue/compiler-sfc'
import { createUnimport } from '../src'

const input = `
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
return _openBlock(), _createElementBlock("div", null, [
_createElementVNode("h1", null, _toDisplayString($setup.count) + " x " + _toDisplayString(_ctx.multiplier) + " = " + _toDisplayString($setup.doubled), 1),
_toDisplayString(_ctx.foo),
_createElementVNode("button", { onClick: $setup.inc }, " Inc ")
]);
}
`
const result = compileTemplate({
id: 'template.vue',
filename: 'template.vue',
source: `
<div>{{ foo }}</div>
<div>{{ foo + 1 }}</div>
<div v-if="foo"></div>
<div v-if="foo === 1"></div>
<div @click="foo"></div>
`,
compilerOptions: {
hoistStatic: false
}
})

describe('vue-template', () => {
const ctx = createUnimport({
imports: [
{ name: 'multiplier', from: 'foo', as: 'multiplier' }
{ name: 'foo', from: 'foo', as: 'foo' }
],
addons: {
vueTemplate: true
}
})

test('inject', async () => {
expect((await ctx.injectImports(input, 'a.vue')).code.toString()).toMatchInlineSnapshot(`
"import { multiplier as __unimport_multiplier } from 'foo';
function _sfc_render(_ctx, _cache, \$props, \$setup, \$data, \$options) {
return _openBlock(), _createElementBlock(\\"div\\", null, [
_createElementVNode(\\"h1\\", null, _toDisplayString(\$setup.count) + \\" x \\" + _toDisplayString(__unimport_multiplier) + \\" = \\" + _toDisplayString(\$setup.doubled), 1),
_toDisplayString(_ctx.foo),
_createElementVNode(\\"button\\", { onClick: \$setup.inc }, \\" Inc \\")
]);
}
"
expect(result.code).toMatchInlineSnapshot(`
"import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, Fragment as _Fragment } from \\"vue\\"

export function render(_ctx, _cache) {
return (_openBlock(), _createElementBlock(_Fragment, null, [
_createElementVNode(\\"div\\", null, _toDisplayString(_ctx.foo), 1 /* TEXT */),
_createElementVNode(\\"div\\", null, _toDisplayString(_ctx.foo + 1), 1 /* TEXT */),
(_ctx.foo)
? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 }))
: _createCommentVNode(\\"v-if\\", true),
(_ctx.foo === 1)
? (_openBlock(), _createElementBlock(\\"div\\", { key: 1 }))
: _createCommentVNode(\\"v-if\\", true),
_createElementVNode(\\"div\\", {
onClick: _cache[0] || (_cache[0] = (...args) => (_ctx.foo && _ctx.foo(...args)))
})
], 64 /* STABLE_FRAGMENT */))
}"
`)
expect((await ctx.injectImports(result.code, 'a.vue')).code.toString()).toMatchInlineSnapshot(`
"import { foo as _unimport_foo } from 'foo';
import { unref as _unimport_unref_ } from 'vue';import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock, createCommentVNode as _createCommentVNode, Fragment as _Fragment } from \\"vue\\"

export function render(_ctx, _cache) {
return (_openBlock(), _createElementBlock(_Fragment, null, [
_createElementVNode(\\"div\\", null, _toDisplayString(_unimport_unref_(_unimport_foo)), 1 /* TEXT */),
_createElementVNode(\\"div\\", null, _toDisplayString(_unimport_unref_(_unimport_foo) + 1), 1 /* TEXT */),
(_unimport_unref_(_unimport_foo))
? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 }))
: _createCommentVNode(\\"v-if\\", true),
(_unimport_unref_(_unimport_foo) === 1)
? (_openBlock(), _createElementBlock(\\"div\\", { key: 1 }))
: _createCommentVNode(\\"v-if\\", true),
_createElementVNode(\\"div\\", {
onClick: _cache[0] || (_cache[0] = (...args) => (_unimport_unref_(_unimport_foo) && _unimport_unref_(_unimport_foo)(...args)))
})
], 64 /* STABLE_FRAGMENT */))
}"
`)
})

test('dts', () => {
expect(ctx.generateTypeDecarations()).toMatchInlineSnapshot(`
"export {}
declare global {
const multiplier: typeof import('foo')['multiplier']
const foo: typeof import('foo')['foo']
}
// for vue template auto import
import { UnwrapRef } from 'vue'
declare module 'vue' {
interface ComponentCustomProperties {
multiplier: typeof import('foo')['multiplier']
readonly foo: UnwrapRef<typeof import('foo')['foo']>
}
}
"
Expand Down