feat(reactivity-transform): rename @vue/ref-transform to @vue/reactivity-transform
This commit is contained in:
121
packages/reactivity-transform/README.md
Normal file
121
packages/reactivity-transform/README.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# @vue/reactivity-transform
|
||||
|
||||
> ⚠️ This is experimental and currently only provided for testing and feedback. It may break during patches or even be removed. Use at your own risk!
|
||||
>
|
||||
> Follow https://github.com/vuejs/rfcs/discussions/369 for details and updates.
|
||||
|
||||
## Basic Rules
|
||||
|
||||
- Ref-creating APIs have `$`-prefixed versions that create reactive variables instead. They also do not need to be explicitly imported. These include:
|
||||
- `ref`
|
||||
- `computed`
|
||||
- `shallowRef`
|
||||
- `customRef`
|
||||
- `toRef`
|
||||
- `$()` can be used to destructure an object into reactive variables, or turn existing refs into reactive variables
|
||||
- `$$()` to "escape" the transform, which allows access to underlying refs
|
||||
|
||||
```js
|
||||
import { watchEffect } from 'vue'
|
||||
|
||||
// bind ref as a variable
|
||||
let count = $ref(0)
|
||||
|
||||
watchEffect(() => {
|
||||
// no need for .value
|
||||
console.log(count)
|
||||
})
|
||||
|
||||
// assignments are reactive
|
||||
count++
|
||||
|
||||
// get the actual ref
|
||||
console.log($$(count)) // { value: 1 }
|
||||
```
|
||||
|
||||
Macros can be optionally imported to make it more explicit:
|
||||
|
||||
```js
|
||||
// not necessary, but also works
|
||||
import { $, $ref } from 'vue/macros'
|
||||
|
||||
let count = $ref(0)
|
||||
const { x, y } = $(useMouse())
|
||||
```
|
||||
|
||||
### Global Types
|
||||
|
||||
To enable types for the macros globally, include the following in a `.d.ts` file:
|
||||
|
||||
```ts
|
||||
/// <reference types="vue/macros-global" />
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
This package is the lower-level transform that can be used standalone. Higher-level tooling (e.g. `@vitejs/plugin-vue` and `vue-loader`) will provide integration via options.
|
||||
|
||||
### `shouldTransform`
|
||||
|
||||
Can be used to do a cheap check to determine whether full transform should be performed.
|
||||
|
||||
```js
|
||||
import { shouldTransform } from '@vue/reactivity-transform'
|
||||
|
||||
shouldTransform(`let a = ref(0)`) // false
|
||||
shouldTransform(`let a = $ref(0)`) // true
|
||||
```
|
||||
|
||||
### `transform`
|
||||
|
||||
```js
|
||||
import { transform } from '@vue/reactivity-transform'
|
||||
|
||||
const src = `let a = $ref(0); a++`
|
||||
const {
|
||||
code, // import { ref as _ref } from 'vue'; let a = (ref(0)); a.value++"
|
||||
map
|
||||
} = transform(src, {
|
||||
filename: 'foo.ts',
|
||||
sourceMap: true,
|
||||
|
||||
// @babel/parser plugins to enable.
|
||||
// 'typescript' and 'jsx' will be auto-inferred from filename if provided,
|
||||
// so in most cases explicit parserPlugins are not necessary
|
||||
parserPlugins: [
|
||||
/* ... */
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
**Options**
|
||||
|
||||
```ts
|
||||
interface RefTransformOptions {
|
||||
filename?: string
|
||||
sourceMap?: boolean // default: false
|
||||
parserPlugins?: ParserPlugin[]
|
||||
importHelpersFrom?: string // default: "vue"
|
||||
}
|
||||
```
|
||||
|
||||
### `transformAST`
|
||||
|
||||
Transform with an existing Babel AST + MagicString instance. This is used internally by `@vue/compiler-sfc` to avoid double parse/transform cost.
|
||||
|
||||
```js
|
||||
import { transformAST } from '@vue/reactivity-transform'
|
||||
import { parse } from '@babel/parser'
|
||||
import MagicString from 'magic-string'
|
||||
|
||||
const src = `let a = $ref(0); a++`
|
||||
const ast = parse(src, { sourceType: 'module' })
|
||||
const s = new MagicString(src)
|
||||
|
||||
const {
|
||||
rootRefs, // ['a']
|
||||
importedHelpers // ['ref']
|
||||
} = transformAST(ast, s)
|
||||
|
||||
console.log(s.toString()) // let a = _ref(0); a.value++
|
||||
```
|
||||
@@ -0,0 +1,235 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`$ unwrapping 1`] = `
|
||||
"
|
||||
import { ref, shallowRef } from 'vue'
|
||||
let foo = (ref())
|
||||
let a = (ref(1))
|
||||
let b = (shallowRef({
|
||||
count: 0
|
||||
}))
|
||||
let c = () => {}
|
||||
let d
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`$$ 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1)
|
||||
const b = (a)
|
||||
const c = ({ a })
|
||||
callExternal((a))
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`$computed declaration 1`] = `
|
||||
"import { computed as _computed } from 'vue'
|
||||
|
||||
let a = _computed(() => 1)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`$ref & $shallowRef declarations 1`] = `
|
||||
"import { ref as _ref, shallowRef as _shallowRef } from 'vue'
|
||||
|
||||
let foo = _ref()
|
||||
let a = _ref(1)
|
||||
let b = _shallowRef({
|
||||
count: 0
|
||||
})
|
||||
let c = () => {}
|
||||
let d
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`accessing ref binding 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1)
|
||||
console.log(a.value)
|
||||
function get() {
|
||||
return a.value + 1
|
||||
}
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`array destructure 1`] = `
|
||||
"import { ref as _ref, toRef as _toRef } from 'vue'
|
||||
|
||||
let n = _ref(1), __$temp_1 = (useFoo()),
|
||||
a = _toRef(__$temp_1, 0),
|
||||
b = _toRef(__$temp_1, 1, 1)
|
||||
console.log(n.value, a.value, b.value)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`handle TS casting syntax 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1)
|
||||
console.log(a.value!)
|
||||
console.log(a.value! + 1)
|
||||
console.log(a.value as number)
|
||||
console.log((a.value as number) + 1)
|
||||
console.log(<number>a.value)
|
||||
console.log(<number>a.value + 1)
|
||||
console.log(a.value! + (a.value as number))
|
||||
console.log(a.value! + <number>a.value)
|
||||
console.log((a.value as number) + <number>a.value)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`macro import alias and removal 1`] = `
|
||||
"import { ref as _ref, toRef as _toRef } from 'vue'
|
||||
|
||||
|
||||
|
||||
let a = _ref(1)
|
||||
const __$temp_1 = (useMouse()),
|
||||
x = _toRef(__$temp_1, 'x'),
|
||||
y = _toRef(__$temp_1, 'y')
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`mixing $ref & $computed declarations 1`] = `
|
||||
"import { ref as _ref, computed as _computed } from 'vue'
|
||||
|
||||
let a = _ref(1), b = _computed(() => a.value + 1)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`multi $ref declarations 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1), b = _ref(2), c = _ref({
|
||||
count: 0
|
||||
})
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`mutating ref binding 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1)
|
||||
let b = _ref({ count: 0 })
|
||||
function inc() {
|
||||
a.value++
|
||||
a.value = a.value + 1
|
||||
b.value.count++
|
||||
b.value.count = b.value.count + 1
|
||||
;({ a: a.value } = { a: 2 })
|
||||
;[a.value] = [1]
|
||||
}
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`nested destructure 1`] = `
|
||||
"import { toRef as _toRef } from 'vue'
|
||||
|
||||
let __$temp_1 = (useFoo()),
|
||||
b = _toRef(__$temp_1[0].a, 'b')
|
||||
let __$temp_2 = (useBar()),
|
||||
d = _toRef(__$temp_2.c, 0),
|
||||
e = _toRef(__$temp_2.c, 1)
|
||||
console.log(b.value, d.value, e.value)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`nested scopes 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(0)
|
||||
let b = _ref(0)
|
||||
let c = 0
|
||||
|
||||
a.value++ // outer a
|
||||
b.value++ // outer b
|
||||
c++ // outer c
|
||||
|
||||
let bar = _ref(0)
|
||||
bar.value++ // outer bar
|
||||
|
||||
function foo({ a }) {
|
||||
a++ // inner a
|
||||
b.value++ // inner b
|
||||
let c = _ref(0)
|
||||
c.value++ // inner c
|
||||
let d = _ref(0)
|
||||
|
||||
function bar(c) {
|
||||
c++ // nested c
|
||||
d.value++ // nested d
|
||||
}
|
||||
bar() // inner bar
|
||||
|
||||
if (true) {
|
||||
let a = _ref(0)
|
||||
a.value++ // if block a
|
||||
}
|
||||
|
||||
return ({ a, b, c, d })
|
||||
}
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`object destructure 1`] = `
|
||||
"import { ref as _ref, toRef as _toRef } from 'vue'
|
||||
|
||||
let n = _ref(1), __$temp_1 = (useFoo()),
|
||||
a = _toRef(__$temp_1, 'a'),
|
||||
c = _toRef(__$temp_1, 'b'),
|
||||
d = _toRef(__$temp_1, 'd', 1),
|
||||
f = _toRef(__$temp_1, 'e', 2),
|
||||
h = _toRef(__$temp_1, g)
|
||||
let __$temp_2 = (useSomthing(() => 1)),
|
||||
foo = _toRef(__$temp_2, 'foo');
|
||||
console.log(n.value, a.value, c.value, d.value, f.value, h.value, foo.value)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`object destructure w/ mid-path default values 1`] = `
|
||||
"import { toRef as _toRef } from 'vue'
|
||||
|
||||
const __$temp_1 = (useFoo()),
|
||||
b = _toRef((__$temp_1.a || { b: 123 }), 'b')
|
||||
console.log(b.value)
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`should not rewrite scope variable 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
|
||||
let a = _ref(1)
|
||||
let b = _ref(1)
|
||||
let d = _ref(1)
|
||||
const e = 1
|
||||
function test() {
|
||||
const a = 2
|
||||
console.log(a)
|
||||
console.log(b.value)
|
||||
let c = { c: 3 }
|
||||
console.log(c)
|
||||
console.log(d.value)
|
||||
console.log(e)
|
||||
}
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`should not rewrite type identifiers 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
const props = defineProps<{msg: string; ids?: string[]}>()
|
||||
let ids = _ref([])"
|
||||
`;
|
||||
|
||||
exports[`using ref binding in property shorthand 1`] = `
|
||||
"import { ref as _ref } from 'vue'
|
||||
|
||||
let a = _ref(1)
|
||||
const b = { a: a.value }
|
||||
function test() {
|
||||
const { a } = b
|
||||
}
|
||||
"
|
||||
`;
|
||||
423
packages/reactivity-transform/__tests__/refTransform.spec.ts
Normal file
423
packages/reactivity-transform/__tests__/refTransform.spec.ts
Normal file
@@ -0,0 +1,423 @@
|
||||
import { parse } from '@babel/parser'
|
||||
import { transform } from '../src'
|
||||
|
||||
function assertCode(code: string) {
|
||||
// parse the generated code to make sure it is valid
|
||||
try {
|
||||
parse(code, {
|
||||
sourceType: 'module',
|
||||
plugins: ['typescript']
|
||||
})
|
||||
} catch (e: any) {
|
||||
console.log(code)
|
||||
throw e
|
||||
}
|
||||
expect(code).toMatchSnapshot()
|
||||
}
|
||||
|
||||
test('$ unwrapping', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
import { ref, shallowRef } from 'vue'
|
||||
let foo = $(ref())
|
||||
let a = $(ref(1))
|
||||
let b = $(shallowRef({
|
||||
count: 0
|
||||
}))
|
||||
let c = () => {}
|
||||
let d
|
||||
`)
|
||||
expect(code).not.toMatch(`$(ref())`)
|
||||
expect(code).not.toMatch(`$(ref(1))`)
|
||||
expect(code).not.toMatch(`$(shallowRef({`)
|
||||
expect(code).toMatch(`let foo = (ref())`)
|
||||
expect(code).toMatch(`let a = (ref(1))`)
|
||||
expect(code).toMatch(`
|
||||
let b = (shallowRef({
|
||||
count: 0
|
||||
}))
|
||||
`)
|
||||
// normal declarations left untouched
|
||||
expect(code).toMatch(`let c = () => {}`)
|
||||
expect(code).toMatch(`let d`)
|
||||
expect(rootRefs).toStrictEqual(['foo', 'a', 'b'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('$ref & $shallowRef declarations', () => {
|
||||
const { code, rootRefs, importedHelpers } = transform(`
|
||||
let foo = $ref()
|
||||
let a = $ref(1)
|
||||
let b = $shallowRef({
|
||||
count: 0
|
||||
})
|
||||
let c = () => {}
|
||||
let d
|
||||
`)
|
||||
expect(code).toMatch(
|
||||
`import { ref as _ref, shallowRef as _shallowRef } from 'vue'`
|
||||
)
|
||||
expect(code).not.toMatch(`$ref()`)
|
||||
expect(code).not.toMatch(`$ref(1)`)
|
||||
expect(code).not.toMatch(`$shallowRef({`)
|
||||
expect(code).toMatch(`let foo = _ref()`)
|
||||
expect(code).toMatch(`let a = _ref(1)`)
|
||||
expect(code).toMatch(`
|
||||
let b = _shallowRef({
|
||||
count: 0
|
||||
})
|
||||
`)
|
||||
// normal declarations left untouched
|
||||
expect(code).toMatch(`let c = () => {}`)
|
||||
expect(code).toMatch(`let d`)
|
||||
expect(rootRefs).toStrictEqual(['foo', 'a', 'b'])
|
||||
expect(importedHelpers).toStrictEqual(['ref', 'shallowRef'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('multi $ref declarations', () => {
|
||||
const { code, rootRefs, importedHelpers } = transform(`
|
||||
let a = $ref(1), b = $ref(2), c = $ref({
|
||||
count: 0
|
||||
})
|
||||
`)
|
||||
expect(code).toMatch(`
|
||||
let a = _ref(1), b = _ref(2), c = _ref({
|
||||
count: 0
|
||||
})
|
||||
`)
|
||||
expect(rootRefs).toStrictEqual(['a', 'b', 'c'])
|
||||
expect(importedHelpers).toStrictEqual(['ref'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('$computed declaration', () => {
|
||||
const { code, rootRefs, importedHelpers } = transform(`
|
||||
let a = $computed(() => 1)
|
||||
`)
|
||||
expect(code).toMatch(`
|
||||
let a = _computed(() => 1)
|
||||
`)
|
||||
expect(rootRefs).toStrictEqual(['a'])
|
||||
expect(importedHelpers).toStrictEqual(['computed'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('mixing $ref & $computed declarations', () => {
|
||||
const { code, rootRefs, importedHelpers } = transform(`
|
||||
let a = $ref(1), b = $computed(() => a + 1)
|
||||
`)
|
||||
expect(code).toMatch(`
|
||||
let a = _ref(1), b = _computed(() => a.value + 1)
|
||||
`)
|
||||
expect(rootRefs).toStrictEqual(['a', 'b'])
|
||||
expect(importedHelpers).toStrictEqual(['ref', 'computed'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('accessing ref binding', () => {
|
||||
const { code } = transform(`
|
||||
let a = $ref(1)
|
||||
console.log(a)
|
||||
function get() {
|
||||
return a + 1
|
||||
}
|
||||
`)
|
||||
expect(code).toMatch(`console.log(a.value)`)
|
||||
expect(code).toMatch(`return a.value + 1`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('cases that should not append .value', () => {
|
||||
const { code } = transform(`
|
||||
let a = $ref(1)
|
||||
console.log(b.a)
|
||||
function get(a) {
|
||||
return a + 1
|
||||
}
|
||||
`)
|
||||
expect(code).not.toMatch(`a.value`)
|
||||
})
|
||||
|
||||
test('mutating ref binding', () => {
|
||||
const { code } = transform(`
|
||||
let a = $ref(1)
|
||||
let b = $ref({ count: 0 })
|
||||
function inc() {
|
||||
a++
|
||||
a = a + 1
|
||||
b.count++
|
||||
b.count = b.count + 1
|
||||
;({ a } = { a: 2 })
|
||||
;[a] = [1]
|
||||
}
|
||||
`)
|
||||
expect(code).toMatch(`a.value++`)
|
||||
expect(code).toMatch(`a.value = a.value + 1`)
|
||||
expect(code).toMatch(`b.value.count++`)
|
||||
expect(code).toMatch(`b.value.count = b.value.count + 1`)
|
||||
expect(code).toMatch(`;({ a: a.value } = { a: 2 })`)
|
||||
expect(code).toMatch(`;[a.value] = [1]`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('using ref binding in property shorthand', () => {
|
||||
const { code } = transform(`
|
||||
let a = $ref(1)
|
||||
const b = { a }
|
||||
function test() {
|
||||
const { a } = b
|
||||
}
|
||||
`)
|
||||
expect(code).toMatch(`const b = { a: a.value }`)
|
||||
// should not convert destructure
|
||||
expect(code).toMatch(`const { a } = b`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('should not rewrite scope variable', () => {
|
||||
const { code } = transform(`
|
||||
|
||||
let a = $ref(1)
|
||||
let b = $ref(1)
|
||||
let d = $ref(1)
|
||||
const e = 1
|
||||
function test() {
|
||||
const a = 2
|
||||
console.log(a)
|
||||
console.log(b)
|
||||
let c = { c: 3 }
|
||||
console.log(c)
|
||||
console.log(d)
|
||||
console.log(e)
|
||||
}
|
||||
`)
|
||||
expect(code).toMatch('console.log(a)')
|
||||
expect(code).toMatch('console.log(b.value)')
|
||||
expect(code).toMatch('console.log(c)')
|
||||
expect(code).toMatch('console.log(d.value)')
|
||||
expect(code).toMatch('console.log(e)')
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('object destructure', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
let n = $ref(1), { a, b: c, d = 1, e: f = 2, [g]: h } = $(useFoo())
|
||||
let { foo } = $(useSomthing(() => 1));
|
||||
console.log(n, a, c, d, f, h, foo)
|
||||
`)
|
||||
expect(code).toMatch(`a = _toRef(__$temp_1, 'a')`)
|
||||
expect(code).toMatch(`c = _toRef(__$temp_1, 'b')`)
|
||||
expect(code).toMatch(`d = _toRef(__$temp_1, 'd', 1)`)
|
||||
expect(code).toMatch(`f = _toRef(__$temp_1, 'e', 2)`)
|
||||
expect(code).toMatch(`h = _toRef(__$temp_1, g)`)
|
||||
expect(code).toMatch(`foo = _toRef(__$temp_2, 'foo')`)
|
||||
expect(code).toMatch(
|
||||
`console.log(n.value, a.value, c.value, d.value, f.value, h.value, foo.value)`
|
||||
)
|
||||
expect(rootRefs).toStrictEqual(['n', 'a', 'c', 'd', 'f', 'h', 'foo'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('object destructure w/ mid-path default values', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
const { a: { b } = { b: 123 }} = $(useFoo())
|
||||
console.log(b)
|
||||
`)
|
||||
expect(code).toMatch(`b = _toRef((__$temp_1.a || { b: 123 }), 'b')`)
|
||||
expect(code).toMatch(`console.log(b.value)`)
|
||||
expect(rootRefs).toStrictEqual(['b'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('array destructure', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
let n = $ref(1), [a, b = 1] = $(useFoo())
|
||||
console.log(n, a, b)
|
||||
`)
|
||||
expect(code).toMatch(`a = _toRef(__$temp_1, 0)`)
|
||||
expect(code).toMatch(`b = _toRef(__$temp_1, 1, 1)`)
|
||||
expect(code).toMatch(`console.log(n.value, a.value, b.value)`)
|
||||
expect(rootRefs).toStrictEqual(['n', 'a', 'b'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('nested destructure', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
let [{ a: { b }}] = $(useFoo())
|
||||
let { c: [d, e] } = $(useBar())
|
||||
console.log(b, d, e)
|
||||
`)
|
||||
expect(code).toMatch(`b = _toRef(__$temp_1[0].a, 'b')`)
|
||||
expect(code).toMatch(`d = _toRef(__$temp_2.c, 0)`)
|
||||
expect(code).toMatch(`e = _toRef(__$temp_2.c, 1)`)
|
||||
expect(rootRefs).toStrictEqual(['b', 'd', 'e'])
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('$$', () => {
|
||||
const { code } = transform(`
|
||||
let a = $ref(1)
|
||||
const b = $$(a)
|
||||
const c = $$({ a })
|
||||
callExternal($$(a))
|
||||
`)
|
||||
expect(code).toMatch(`const b = (a)`)
|
||||
expect(code).toMatch(`const c = ({ a })`)
|
||||
expect(code).toMatch(`callExternal((a))`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('nested scopes', () => {
|
||||
const { code, rootRefs } = transform(`
|
||||
let a = $ref(0)
|
||||
let b = $ref(0)
|
||||
let c = 0
|
||||
|
||||
a++ // outer a
|
||||
b++ // outer b
|
||||
c++ // outer c
|
||||
|
||||
let bar = $ref(0)
|
||||
bar++ // outer bar
|
||||
|
||||
function foo({ a }) {
|
||||
a++ // inner a
|
||||
b++ // inner b
|
||||
let c = $ref(0)
|
||||
c++ // inner c
|
||||
let d = $ref(0)
|
||||
|
||||
function bar(c) {
|
||||
c++ // nested c
|
||||
d++ // nested d
|
||||
}
|
||||
bar() // inner bar
|
||||
|
||||
if (true) {
|
||||
let a = $ref(0)
|
||||
a++ // if block a
|
||||
}
|
||||
|
||||
return $$({ a, b, c, d })
|
||||
}
|
||||
`)
|
||||
expect(rootRefs).toStrictEqual(['a', 'b', 'bar'])
|
||||
|
||||
expect(code).toMatch('a.value++ // outer a')
|
||||
expect(code).toMatch('b.value++ // outer b')
|
||||
expect(code).toMatch('c++ // outer c')
|
||||
|
||||
expect(code).toMatch('a++ // inner a') // shadowed by function arg
|
||||
expect(code).toMatch('b.value++ // inner b')
|
||||
expect(code).toMatch('c.value++ // inner c') // shadowed by local ref binding
|
||||
|
||||
expect(code).toMatch('c++ // nested c') // shadowed by inline fn arg
|
||||
expect(code).toMatch(`d.value++ // nested d`)
|
||||
|
||||
expect(code).toMatch(`a.value++ // if block a`) // if block
|
||||
|
||||
expect(code).toMatch(`bar.value++ // outer bar`)
|
||||
// inner bar shadowed by function declaration
|
||||
expect(code).toMatch(`bar() // inner bar`)
|
||||
|
||||
expect(code).toMatch(`return ({ a, b, c, d })`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
//#4062
|
||||
test('should not rewrite type identifiers', () => {
|
||||
const { code } = transform(
|
||||
`const props = defineProps<{msg: string; ids?: string[]}>()
|
||||
let ids = $ref([])`,
|
||||
{
|
||||
parserPlugins: ['typescript']
|
||||
}
|
||||
)
|
||||
expect(code).not.toMatch('.value')
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
// #4254
|
||||
test('handle TS casting syntax', () => {
|
||||
const { code } = transform(
|
||||
`
|
||||
let a = $ref(1)
|
||||
console.log(a!)
|
||||
console.log(a! + 1)
|
||||
console.log(a as number)
|
||||
console.log((a as number) + 1)
|
||||
console.log(<number>a)
|
||||
console.log(<number>a + 1)
|
||||
console.log(a! + (a as number))
|
||||
console.log(a! + <number>a)
|
||||
console.log((a as number) + <number>a)
|
||||
`,
|
||||
{
|
||||
parserPlugins: ['typescript']
|
||||
}
|
||||
)
|
||||
expect(code).toMatch('console.log(a.value!)')
|
||||
expect(code).toMatch('console.log(a.value as number)')
|
||||
expect(code).toMatch('console.log(<number>a.value)')
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
test('macro import alias and removal', () => {
|
||||
const { code } = transform(
|
||||
`
|
||||
import { $ as fromRefs, $ref } from 'vue/macros'
|
||||
|
||||
let a = $ref(1)
|
||||
const { x, y } = fromRefs(useMouse())
|
||||
`
|
||||
)
|
||||
// should remove imports
|
||||
expect(code).not.toMatch(`from 'vue/macros'`)
|
||||
expect(code).toMatch(`let a = _ref(1)`)
|
||||
expect(code).toMatch(`const __$temp_1 = (useMouse())`)
|
||||
assertCode(code)
|
||||
})
|
||||
|
||||
describe('errors', () => {
|
||||
test('$ref w/ destructure', () => {
|
||||
expect(() => transform(`let { a } = $ref(1)`)).toThrow(
|
||||
`cannot be used with destructure`
|
||||
)
|
||||
})
|
||||
|
||||
test('$computed w/ destructure', () => {
|
||||
expect(() => transform(`let { a } = $computed(() => 1)`)).toThrow(
|
||||
`cannot be used with destructure`
|
||||
)
|
||||
})
|
||||
|
||||
test('warn usage in non-init positions', () => {
|
||||
expect(() =>
|
||||
transform(
|
||||
`let bar = $ref(1)
|
||||
bar = $ref(2)`
|
||||
)
|
||||
).toThrow(`$ref can only be used as the initializer`)
|
||||
|
||||
expect(() => transform(`let bar = { foo: $computed(1) }`)).toThrow(
|
||||
`$computed can only be used as the initializer`
|
||||
)
|
||||
})
|
||||
|
||||
test('not transform the prototype attributes', () => {
|
||||
const { code } = transform(`
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty
|
||||
const hasOwn = (val, key) => hasOwnProperty.call(val, key)
|
||||
`)
|
||||
expect(code).not.toMatch('.value')
|
||||
})
|
||||
|
||||
test('rest element in $() destructure', () => {
|
||||
expect(() => transform(`let { a, ...b } = $(foo())`)).toThrow(
|
||||
`does not support rest element`
|
||||
)
|
||||
expect(() => transform(`let [a, ...b] = $(foo())`)).toThrow(
|
||||
`does not support rest element`
|
||||
)
|
||||
})
|
||||
})
|
||||
7
packages/reactivity-transform/api-extractor.json
Normal file
7
packages/reactivity-transform/api-extractor.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../api-extractor.json",
|
||||
"mainEntryPointFilePath": "./dist/packages/<unscopedPackageName>/src/index.d.ts",
|
||||
"dtsRollup": {
|
||||
"publicTrimmedFilePath": "./dist/<unscopedPackageName>.d.ts"
|
||||
}
|
||||
}
|
||||
40
packages/reactivity-transform/package.json
Normal file
40
packages/reactivity-transform/package.json
Normal file
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@vue/reactivity-transform",
|
||||
"version": "3.2.24",
|
||||
"description": "@vue/reactivity-transform",
|
||||
"main": "dist/reactivity-transform.cjs.js",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"buildOptions": {
|
||||
"formats": [
|
||||
"cjs"
|
||||
],
|
||||
"prod": false
|
||||
},
|
||||
"types": "dist/reactivity-transform.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vuejs/vue-next.git",
|
||||
"directory": "packages/reactivity-transform"
|
||||
},
|
||||
"keywords": [
|
||||
"vue"
|
||||
],
|
||||
"author": "Evan You",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/vuejs/vue-next/issues"
|
||||
},
|
||||
"homepage": "https://github.com/vuejs/vue-next/tree/dev/packages/reactivity-transform#readme",
|
||||
"dependencies": {
|
||||
"@babel/parser": "^7.15.0",
|
||||
"@vue/compiler-core": "3.2.24",
|
||||
"@vue/shared": "3.2.24",
|
||||
"estree-walker": "^2.0.2",
|
||||
"magic-string": "^0.25.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.15.0"
|
||||
}
|
||||
}
|
||||
3
packages/reactivity-transform/src/babelPlugin.ts
Normal file
3
packages/reactivity-transform/src/babelPlugin.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export function plugin() {
|
||||
// TODO
|
||||
}
|
||||
1
packages/reactivity-transform/src/index.ts
Normal file
1
packages/reactivity-transform/src/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './refTransform'
|
||||
665
packages/reactivity-transform/src/refTransform.ts
Normal file
665
packages/reactivity-transform/src/refTransform.ts
Normal file
@@ -0,0 +1,665 @@
|
||||
import {
|
||||
Node,
|
||||
Identifier,
|
||||
BlockStatement,
|
||||
CallExpression,
|
||||
ObjectPattern,
|
||||
ArrayPattern,
|
||||
Program,
|
||||
VariableDeclarator,
|
||||
Expression
|
||||
} from '@babel/types'
|
||||
import MagicString, { SourceMap } from 'magic-string'
|
||||
import { walk } from 'estree-walker'
|
||||
import {
|
||||
extractIdentifiers,
|
||||
isFunctionType,
|
||||
isInDestructureAssignment,
|
||||
isReferencedIdentifier,
|
||||
isStaticProperty,
|
||||
walkFunctionParams
|
||||
} from '@vue/compiler-core'
|
||||
import { parse, ParserPlugin } from '@babel/parser'
|
||||
import { hasOwn, isArray, isString } from '@vue/shared'
|
||||
|
||||
const CONVERT_SYMBOL = '$'
|
||||
const ESCAPE_SYMBOL = '$$'
|
||||
const shorthands = ['ref', 'computed', 'shallowRef', 'toRef', 'customRef']
|
||||
const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/
|
||||
|
||||
export function shouldTransform(src: string): boolean {
|
||||
return transformCheckRE.test(src)
|
||||
}
|
||||
|
||||
type Scope = Record<string, boolean | 'prop'>
|
||||
|
||||
export interface RefTransformOptions {
|
||||
filename?: string
|
||||
sourceMap?: boolean
|
||||
parserPlugins?: ParserPlugin[]
|
||||
importHelpersFrom?: string
|
||||
}
|
||||
|
||||
export interface RefTransformResults {
|
||||
code: string
|
||||
map: SourceMap | null
|
||||
rootRefs: string[]
|
||||
importedHelpers: string[]
|
||||
}
|
||||
|
||||
export function transform(
|
||||
src: string,
|
||||
{
|
||||
filename,
|
||||
sourceMap,
|
||||
parserPlugins,
|
||||
importHelpersFrom = 'vue'
|
||||
}: RefTransformOptions = {}
|
||||
): RefTransformResults {
|
||||
const plugins: ParserPlugin[] = parserPlugins || []
|
||||
if (filename) {
|
||||
if (/\.tsx?$/.test(filename)) {
|
||||
plugins.push('typescript')
|
||||
}
|
||||
if (filename.endsWith('x')) {
|
||||
plugins.push('jsx')
|
||||
}
|
||||
}
|
||||
|
||||
const ast = parse(src, {
|
||||
sourceType: 'module',
|
||||
plugins
|
||||
})
|
||||
const s = new MagicString(src)
|
||||
const res = transformAST(ast.program, s, 0)
|
||||
|
||||
// inject helper imports
|
||||
if (res.importedHelpers.length) {
|
||||
s.prepend(
|
||||
`import { ${res.importedHelpers
|
||||
.map(h => `${h} as _${h}`)
|
||||
.join(', ')} } from '${importHelpersFrom}'\n`
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
...res,
|
||||
code: s.toString(),
|
||||
map: sourceMap
|
||||
? s.generateMap({
|
||||
source: filename,
|
||||
hires: true,
|
||||
includeContent: true
|
||||
})
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
export function transformAST(
|
||||
ast: Program,
|
||||
s: MagicString,
|
||||
offset = 0,
|
||||
knownRefs?: string[],
|
||||
knownProps?: Record<
|
||||
string, // public prop key
|
||||
{
|
||||
local: string // local identifier, may be different
|
||||
default?: any
|
||||
}
|
||||
>
|
||||
): {
|
||||
rootRefs: string[]
|
||||
importedHelpers: string[]
|
||||
} {
|
||||
// TODO remove when out of experimental
|
||||
warnExperimental()
|
||||
|
||||
let convertSymbol = CONVERT_SYMBOL
|
||||
let escapeSymbol = ESCAPE_SYMBOL
|
||||
|
||||
// macro import handling
|
||||
for (const node of ast.body) {
|
||||
if (
|
||||
node.type === 'ImportDeclaration' &&
|
||||
node.source.value === 'vue/macros'
|
||||
) {
|
||||
// remove macro imports
|
||||
s.remove(node.start! + offset, node.end! + offset)
|
||||
// check aliasing
|
||||
for (const specifier of node.specifiers) {
|
||||
if (specifier.type === 'ImportSpecifier') {
|
||||
const imported = (specifier.imported as Identifier).name
|
||||
const local = specifier.local.name
|
||||
if (local !== imported) {
|
||||
if (imported === ESCAPE_SYMBOL) {
|
||||
escapeSymbol = local
|
||||
} else if (imported === CONVERT_SYMBOL) {
|
||||
convertSymbol = local
|
||||
} else {
|
||||
error(
|
||||
`macro imports for ref-creating methods do not support aliasing.`,
|
||||
specifier
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const importedHelpers = new Set<string>()
|
||||
const rootScope: Scope = {}
|
||||
const scopeStack: Scope[] = [rootScope]
|
||||
let currentScope: Scope = rootScope
|
||||
let escapeScope: CallExpression | undefined // inside $$()
|
||||
const excludedIds = new WeakSet<Identifier>()
|
||||
const parentStack: Node[] = []
|
||||
const propsLocalToPublicMap = Object.create(null)
|
||||
|
||||
if (knownRefs) {
|
||||
for (const key of knownRefs) {
|
||||
rootScope[key] = true
|
||||
}
|
||||
}
|
||||
if (knownProps) {
|
||||
for (const key in knownProps) {
|
||||
const { local } = knownProps[key]
|
||||
rootScope[local] = 'prop'
|
||||
propsLocalToPublicMap[local] = key
|
||||
}
|
||||
}
|
||||
|
||||
function isRefCreationCall(callee: string): string | false {
|
||||
if (callee === convertSymbol) {
|
||||
return convertSymbol
|
||||
}
|
||||
if (callee[0] === '$' && shorthands.includes(callee.slice(1))) {
|
||||
return callee
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function error(msg: string, node: Node) {
|
||||
const e = new Error(msg)
|
||||
;(e as any).node = node
|
||||
throw e
|
||||
}
|
||||
|
||||
function helper(msg: string) {
|
||||
importedHelpers.add(msg)
|
||||
return `_${msg}`
|
||||
}
|
||||
|
||||
function registerBinding(id: Identifier, isRef = false) {
|
||||
excludedIds.add(id)
|
||||
if (currentScope) {
|
||||
currentScope[id.name] = isRef
|
||||
} else {
|
||||
error(
|
||||
'registerBinding called without active scope, something is wrong.',
|
||||
id
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const registerRefBinding = (id: Identifier) => registerBinding(id, true)
|
||||
|
||||
let tempVarCount = 0
|
||||
function genTempVar() {
|
||||
return `__$temp_${++tempVarCount}`
|
||||
}
|
||||
|
||||
function snip(node: Node) {
|
||||
return s.original.slice(node.start! + offset, node.end! + offset)
|
||||
}
|
||||
|
||||
function walkScope(node: Program | BlockStatement, isRoot = false) {
|
||||
for (const stmt of node.body) {
|
||||
if (stmt.type === 'VariableDeclaration') {
|
||||
if (stmt.declare) continue
|
||||
for (const decl of stmt.declarations) {
|
||||
let refCall
|
||||
const isCall =
|
||||
decl.init &&
|
||||
decl.init.type === 'CallExpression' &&
|
||||
decl.init.callee.type === 'Identifier'
|
||||
if (
|
||||
isCall &&
|
||||
(refCall = isRefCreationCall((decl as any).init.callee.name))
|
||||
) {
|
||||
processRefDeclaration(refCall, decl.id, decl.init as CallExpression)
|
||||
} else {
|
||||
const isProps =
|
||||
isRoot &&
|
||||
isCall &&
|
||||
(decl as any).init.callee.name === 'defineProps'
|
||||
for (const id of extractIdentifiers(decl.id)) {
|
||||
if (isProps) {
|
||||
// for defineProps destructure, only exclude them since they
|
||||
// are already passed in as knownProps
|
||||
excludedIds.add(id)
|
||||
} else {
|
||||
registerBinding(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
stmt.type === 'FunctionDeclaration' ||
|
||||
stmt.type === 'ClassDeclaration'
|
||||
) {
|
||||
if (stmt.declare || !stmt.id) continue
|
||||
registerBinding(stmt.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function processRefDeclaration(
|
||||
method: string,
|
||||
id: VariableDeclarator['id'],
|
||||
call: CallExpression
|
||||
) {
|
||||
excludedIds.add(call.callee as Identifier)
|
||||
if (method === convertSymbol) {
|
||||
// $
|
||||
// remove macro
|
||||
s.remove(call.callee.start! + offset, call.callee.end! + offset)
|
||||
if (id.type === 'Identifier') {
|
||||
// single variable
|
||||
registerRefBinding(id)
|
||||
} else if (id.type === 'ObjectPattern') {
|
||||
processRefObjectPattern(id, call)
|
||||
} else if (id.type === 'ArrayPattern') {
|
||||
processRefArrayPattern(id, call)
|
||||
}
|
||||
} else {
|
||||
// shorthands
|
||||
if (id.type === 'Identifier') {
|
||||
registerRefBinding(id)
|
||||
// replace call
|
||||
s.overwrite(
|
||||
call.start! + offset,
|
||||
call.start! + method.length + offset,
|
||||
helper(method.slice(1))
|
||||
)
|
||||
} else {
|
||||
error(`${method}() cannot be used with destructure patterns.`, call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function processRefObjectPattern(
|
||||
pattern: ObjectPattern,
|
||||
call: CallExpression,
|
||||
tempVar?: string,
|
||||
path: PathSegment[] = []
|
||||
) {
|
||||
if (!tempVar) {
|
||||
tempVar = genTempVar()
|
||||
// const { x } = $(useFoo()) --> const __$temp_1 = useFoo()
|
||||
s.overwrite(pattern.start! + offset, pattern.end! + offset, tempVar)
|
||||
}
|
||||
|
||||
for (const p of pattern.properties) {
|
||||
let nameId: Identifier | undefined
|
||||
let key: Expression | string | undefined
|
||||
let defaultValue: Expression | undefined
|
||||
if (p.type === 'ObjectProperty') {
|
||||
if (p.key.start! === p.value.start!) {
|
||||
// shorthand { foo }
|
||||
nameId = p.key as Identifier
|
||||
if (p.value.type === 'Identifier') {
|
||||
// avoid shorthand value identifier from being processed
|
||||
excludedIds.add(p.value)
|
||||
} else if (
|
||||
p.value.type === 'AssignmentPattern' &&
|
||||
p.value.left.type === 'Identifier'
|
||||
) {
|
||||
// { foo = 1 }
|
||||
excludedIds.add(p.value.left)
|
||||
defaultValue = p.value.right
|
||||
}
|
||||
} else {
|
||||
key = p.computed ? p.key : (p.key as Identifier).name
|
||||
if (p.value.type === 'Identifier') {
|
||||
// { foo: bar }
|
||||
nameId = p.value
|
||||
} else if (p.value.type === 'ObjectPattern') {
|
||||
processRefObjectPattern(p.value, call, tempVar, [...path, key])
|
||||
} else if (p.value.type === 'ArrayPattern') {
|
||||
processRefArrayPattern(p.value, call, tempVar, [...path, key])
|
||||
} else if (p.value.type === 'AssignmentPattern') {
|
||||
if (p.value.left.type === 'Identifier') {
|
||||
// { foo: bar = 1 }
|
||||
nameId = p.value.left
|
||||
defaultValue = p.value.right
|
||||
} else if (p.value.left.type === 'ObjectPattern') {
|
||||
processRefObjectPattern(p.value.left, call, tempVar, [
|
||||
...path,
|
||||
[key, p.value.right]
|
||||
])
|
||||
} else if (p.value.left.type === 'ArrayPattern') {
|
||||
processRefArrayPattern(p.value.left, call, tempVar, [
|
||||
...path,
|
||||
[key, p.value.right]
|
||||
])
|
||||
} else {
|
||||
// MemberExpression case is not possible here, ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// rest element { ...foo }
|
||||
error(`reactivity destructure does not support rest elements.`, p)
|
||||
}
|
||||
if (nameId) {
|
||||
registerRefBinding(nameId)
|
||||
// inject toRef() after original replaced pattern
|
||||
const source = pathToString(tempVar, path)
|
||||
const keyStr = isString(key)
|
||||
? `'${key}'`
|
||||
: key
|
||||
? snip(key)
|
||||
: `'${nameId.name}'`
|
||||
const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``
|
||||
s.appendLeft(
|
||||
call.end! + offset,
|
||||
`,\n ${nameId.name} = ${helper(
|
||||
'toRef'
|
||||
)}(${source}, ${keyStr}${defaultStr})`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function processRefArrayPattern(
|
||||
pattern: ArrayPattern,
|
||||
call: CallExpression,
|
||||
tempVar?: string,
|
||||
path: PathSegment[] = []
|
||||
) {
|
||||
if (!tempVar) {
|
||||
// const [x] = $(useFoo()) --> const __$temp_1 = useFoo()
|
||||
tempVar = genTempVar()
|
||||
s.overwrite(pattern.start! + offset, pattern.end! + offset, tempVar)
|
||||
}
|
||||
|
||||
for (let i = 0; i < pattern.elements.length; i++) {
|
||||
const e = pattern.elements[i]
|
||||
if (!e) continue
|
||||
let nameId: Identifier | undefined
|
||||
let defaultValue: Expression | undefined
|
||||
if (e.type === 'Identifier') {
|
||||
// [a] --> [__a]
|
||||
nameId = e
|
||||
} else if (e.type === 'AssignmentPattern') {
|
||||
// [a = 1]
|
||||
nameId = e.left as Identifier
|
||||
defaultValue = e.right
|
||||
} else if (e.type === 'RestElement') {
|
||||
// [...a]
|
||||
error(`reactivity destructure does not support rest elements.`, e)
|
||||
} else if (e.type === 'ObjectPattern') {
|
||||
processRefObjectPattern(e, call, tempVar, [...path, i])
|
||||
} else if (e.type === 'ArrayPattern') {
|
||||
processRefArrayPattern(e, call, tempVar, [...path, i])
|
||||
}
|
||||
if (nameId) {
|
||||
registerRefBinding(nameId)
|
||||
// inject toRef() after original replaced pattern
|
||||
const source = pathToString(tempVar, path)
|
||||
const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``
|
||||
s.appendLeft(
|
||||
call.end! + offset,
|
||||
`,\n ${nameId.name} = ${helper(
|
||||
'toRef'
|
||||
)}(${source}, ${i}${defaultStr})`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type PathSegmentAtom = Expression | string | number
|
||||
|
||||
type PathSegment =
|
||||
| PathSegmentAtom
|
||||
| [PathSegmentAtom, Expression /* default value */]
|
||||
|
||||
function pathToString(source: string, path: PathSegment[]): string {
|
||||
if (path.length) {
|
||||
for (const seg of path) {
|
||||
if (isArray(seg)) {
|
||||
source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`
|
||||
} else {
|
||||
source += segToString(seg)
|
||||
}
|
||||
}
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
function segToString(seg: PathSegmentAtom): string {
|
||||
if (typeof seg === 'number') {
|
||||
return `[${seg}]`
|
||||
} else if (typeof seg === 'string') {
|
||||
return `.${seg}`
|
||||
} else {
|
||||
return snip(seg)
|
||||
}
|
||||
}
|
||||
|
||||
function rewriteId(
|
||||
scope: Scope,
|
||||
id: Identifier,
|
||||
parent: Node,
|
||||
parentStack: Node[]
|
||||
): boolean {
|
||||
if (hasOwn(scope, id.name)) {
|
||||
const bindingType = scope[id.name]
|
||||
if (bindingType) {
|
||||
const isProp = bindingType === 'prop'
|
||||
if (isStaticProperty(parent) && parent.shorthand) {
|
||||
// let binding used in a property shorthand
|
||||
// skip for destructure patterns
|
||||
if (
|
||||
!(parent as any).inPattern ||
|
||||
isInDestructureAssignment(parent, parentStack)
|
||||
) {
|
||||
if (isProp) {
|
||||
if (escapeScope) {
|
||||
// prop binding in $$()
|
||||
// { prop } -> { prop: __prop_prop }
|
||||
registerEscapedPropBinding(id)
|
||||
s.appendLeft(
|
||||
id.end! + offset,
|
||||
`: __props_${propsLocalToPublicMap[id.name]}`
|
||||
)
|
||||
} else {
|
||||
// { prop } -> { prop: __prop.prop }
|
||||
s.appendLeft(
|
||||
id.end! + offset,
|
||||
`: __props.${propsLocalToPublicMap[id.name]}`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// { foo } -> { foo: foo.value }
|
||||
s.appendLeft(id.end! + offset, `: ${id.name}.value`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (isProp) {
|
||||
if (escapeScope) {
|
||||
// x --> __props_x
|
||||
registerEscapedPropBinding(id)
|
||||
s.overwrite(
|
||||
id.start! + offset,
|
||||
id.end! + offset,
|
||||
`__props_${propsLocalToPublicMap[id.name]}`
|
||||
)
|
||||
} else {
|
||||
// x --> __props.x
|
||||
s.overwrite(
|
||||
id.start! + offset,
|
||||
id.end! + offset,
|
||||
`__props.${propsLocalToPublicMap[id.name]}`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// x --> x.value
|
||||
s.appendLeft(id.end! + offset, '.value')
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const propBindingRefs: Record<string, true> = {}
|
||||
function registerEscapedPropBinding(id: Identifier) {
|
||||
if (!propBindingRefs.hasOwnProperty(id.name)) {
|
||||
propBindingRefs[id.name] = true
|
||||
const publicKey = propsLocalToPublicMap[id.name]
|
||||
s.prependRight(
|
||||
offset,
|
||||
`const __props_${publicKey} = ${helper(
|
||||
`toRef`
|
||||
)}(__props, '${publicKey}')\n`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// check root scope first
|
||||
walkScope(ast, true)
|
||||
;(walk as any)(ast, {
|
||||
enter(node: Node, parent?: Node) {
|
||||
parent && parentStack.push(parent)
|
||||
|
||||
// function scopes
|
||||
if (isFunctionType(node)) {
|
||||
scopeStack.push((currentScope = {}))
|
||||
walkFunctionParams(node, registerBinding)
|
||||
if (node.body.type === 'BlockStatement') {
|
||||
walkScope(node.body)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// non-function block scopes
|
||||
if (node.type === 'BlockStatement' && !isFunctionType(parent!)) {
|
||||
scopeStack.push((currentScope = {}))
|
||||
walkScope(node)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
parent &&
|
||||
parent.type.startsWith('TS') &&
|
||||
parent.type !== 'TSAsExpression' &&
|
||||
parent.type !== 'TSNonNullExpression' &&
|
||||
parent.type !== 'TSTypeAssertion'
|
||||
) {
|
||||
return this.skip()
|
||||
}
|
||||
|
||||
if (
|
||||
node.type === 'Identifier' &&
|
||||
// if inside $$(), skip unless this is a destructured prop binding
|
||||
!(escapeScope && rootScope[node.name] !== 'prop') &&
|
||||
isReferencedIdentifier(node, parent!, parentStack) &&
|
||||
!excludedIds.has(node)
|
||||
) {
|
||||
// walk up the scope chain to check if id should be appended .value
|
||||
let i = scopeStack.length
|
||||
while (i--) {
|
||||
if (rewriteId(scopeStack[i], node, parent!, parentStack)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
|
||||
const callee = node.callee.name
|
||||
|
||||
const refCall = isRefCreationCall(callee)
|
||||
if (refCall && (!parent || parent.type !== 'VariableDeclarator')) {
|
||||
return error(
|
||||
`${refCall} can only be used as the initializer of ` +
|
||||
`a variable declaration.`,
|
||||
node
|
||||
)
|
||||
}
|
||||
|
||||
if (callee === escapeSymbol) {
|
||||
s.remove(node.callee.start! + offset, node.callee.end! + offset)
|
||||
escapeScope = node
|
||||
}
|
||||
|
||||
// TODO remove when out of experimental
|
||||
if (callee === '$raw') {
|
||||
error(
|
||||
`$raw() has been replaced by $$(). ` +
|
||||
`See ${RFC_LINK} for latest updates.`,
|
||||
node
|
||||
)
|
||||
}
|
||||
if (callee === '$fromRef') {
|
||||
error(
|
||||
`$fromRef() has been replaced by $(). ` +
|
||||
`See ${RFC_LINK} for latest updates.`,
|
||||
node
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
leave(node: Node, parent?: Node) {
|
||||
parent && parentStack.pop()
|
||||
if (
|
||||
(node.type === 'BlockStatement' && !isFunctionType(parent!)) ||
|
||||
isFunctionType(node)
|
||||
) {
|
||||
scopeStack.pop()
|
||||
currentScope = scopeStack[scopeStack.length - 1] || null
|
||||
}
|
||||
if (node === escapeScope) {
|
||||
escapeScope = undefined
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
rootRefs: Object.keys(rootScope).filter(key => rootScope[key] === true),
|
||||
importedHelpers: [...importedHelpers]
|
||||
}
|
||||
}
|
||||
|
||||
const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`
|
||||
const hasWarned: Record<string, boolean> = {}
|
||||
|
||||
function warnExperimental() {
|
||||
// eslint-disable-next-line
|
||||
if (typeof window !== 'undefined') {
|
||||
return
|
||||
}
|
||||
warnOnce(
|
||||
`Reactivity transform is an experimental feature.\n` +
|
||||
`Experimental features may change behavior between patch versions.\n` +
|
||||
`It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
|
||||
`You can follow the proposal's status at ${RFC_LINK}.`
|
||||
)
|
||||
}
|
||||
|
||||
function warnOnce(msg: string) {
|
||||
const isNodeProd =
|
||||
typeof process !== 'undefined' && process.env.NODE_ENV === 'production'
|
||||
if (!isNodeProd && !__TEST__ && !hasWarned[msg]) {
|
||||
hasWarned[msg] = true
|
||||
warn(msg)
|
||||
}
|
||||
}
|
||||
|
||||
function warn(msg: string) {
|
||||
console.warn(
|
||||
`\x1b[1m\x1b[33m[@vue/ref-transform]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user