提交 67782af8 编写于 作者: L longsi

feat(uni-mp-xhs): 新增小红书小程序的支持

上级 3b56e8f2
......@@ -10,7 +10,7 @@
"build": "node scripts/build.js",
"build:h5": "node scripts/build.js uni-app uts uni-uts-v1 uni-app-uvue uni-cli-shared uni-h5 uni-i18n uni-stat uni-shared uni-h5-vite vite-plugin-uni",
"build:app": "node scripts/build.js uni-app-plus uni-app-vite uni-app-vue uni-app-uvue",
"build:mp": "node scripts/build.js uni-mp-vue uni-mp-vite uni-mp-compiler uni-mp-alipay uni-mp-baidu uni-mp-kuaishou uni-mp-lark uni-mp-qq uni-mp-toutiao uni-mp-weixin uni-quickapp-webview",
"build:mp": "node scripts/build.js uni-mp-vue uni-mp-vite uni-mp-compiler uni-mp-alipay uni-mp-baidu uni-mp-kuaishou uni-mp-lark uni-mp-qq uni-mp-toutiao uni-mp-weixin uni-mp-xhs uni-quickapp-webview",
"size": "npm run build size-check",
"lint": "eslint packages/*/src/**/*.ts",
"format": "prettier --write --parser typescript \"packages/**/*.ts?(x)\"",
......
......@@ -8,6 +8,7 @@ declare var swan: any
declare var qq: any
declare var ks: any
declare var jd: any
declare var xhs: any
declare var __NVUE__: undefined | boolean
declare var __PLATFORM__: UniApp.PLATFORM
declare var __PLATFORM_PREFIX__:
......@@ -19,6 +20,7 @@ declare var __PLATFORM_PREFIX__:
| 'qa'
| 'ks'
| 'jd'
| 'xhs'
declare var __GLOBAL__: Record<string, any>
// importMeta(es|cjs)
......
......@@ -197,6 +197,7 @@ declare namespace UniNamespace {
'mp-kuaishou'?: PagesJsonPageStyle
'mp-lark'?: PagesJsonPageStyle
'mp-jd'?: PagesJsonPageStyle
'mp-xhs'?: PagesJsonPageStyle
'quickapp-webview'?: PagesJsonPageStyle
'quickapp-webview-huawei'?: PagesJsonPageStyle
'quickapp-webview-union'?: PagesJsonPageStyle
......
......@@ -32,7 +32,11 @@ function createEmitFn(oldEmit: Function, ctx: Record<string, any>) {
if (scope && event) {
const detail: Record<string, any> = { __args__: args }
// 百度小程序,快手小程序,自定义组件不能绑定动态事件
if (__PLATFORM__ === 'mp-baidu' || __PLATFORM__ === 'mp-kuaishou') {
if (
__PLATFORM__ === 'mp-baidu' ||
__PLATFORM__ === 'mp-kuaishou' ||
__PLATFORM__ === 'mp-xhs'
) {
detail.__ins__ = scope
}
if (__PLATFORM__ === 'mp-jd') {
......
......@@ -18,7 +18,9 @@ export const compressImage: MPProtocol = {
toArgs: WechatMiniprogram.CompressImageOption
) {
// https://developers.weixin.qq.com/community/develop/doc/000c08940c865011298e0a43256800?highLine=compressHeight
// @ts-expect-error
if (fromArgs.compressedHeight && !toArgs.compressHeight) {
// @ts-expect-error
toArgs.compressHeight = fromArgs.compressedHeight
}
// @ts-expect-error
......
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\ No newline at end of file
import { assert } from './testUtils'
describe('mp-xhs: transform component', () => {
test('lazy element: textarea', () => {
assert(
`<textarea></textarea>`,
`<textarea></textarea>`,
`(_ctx, _cache) => {
return {}
}`
)
assert(
`<textarea @input="input"></textarea>`,
`<block xhs:if="{{r0}}"><textarea bindinput="__e" data-e-o="{{a}}"></textarea></block>`,
`(_ctx, _cache) => {
return { a: { 'input': _o(_ctx.input) } }
}`
)
assert(
`<textarea v-model="text"></textarea>`,
`<block xhs:if="{{r0}}"><textarea value="{{a}}" bindinput="{{b}}"></textarea></block>`,
`(_ctx, _cache) => {
return { a: _ctx.text, b: _o($event => _ctx.text = $event.detail.value) }
}`
)
assert(
`<textarea v-if="ok1" @input="input"/><textarea v-else-if="ok2"/><textarea v-else @input="input"/>`,
`<textarea xhs:if="{{a}}" bindinput="__e" data-e-o="{{b}}"/><textarea xhs:elif="{{c}}"/><block xhs:else><textarea xhs:if="{{r0}}" bindinput="__e" data-e-o="{{d}}"/></block>`,
`(_ctx, _cache) => {
return _e({ a: _ctx.ok1 }, _ctx.ok1 ? { b: { 'input': _o(_ctx.input) } } : _ctx.ok2 ? {} : { d: { 'input': _o(_ctx.input) } }, { c: _ctx.ok2 })
}`
)
})
test('lazy element: editor', () => {
assert(
`<editor/>`,
`<editor/>`,
`(_ctx, _cache) => {
return {}
}`
)
assert(
`<editor @ready="ready"/>`,
`<block xhs:if="{{r0}}"><editor bindready="__e" data-e-o="{{a}}"/></block>`,
`(_ctx, _cache) => {
return { a: { 'ready': _o(_ctx.ready) } }
}`
)
assert(
`<editor v-if="ok1" @ready="ready"/><editor v-else-if="ok2"/><editor v-else/>`,
`<editor xhs:if="{{a}}" bindready="__e" data-e-o="{{b}}"/><editor xhs:elif="{{c}}"/><editor xhs:else/>`,
`(_ctx, _cache) => {
return _e({ a: _ctx.ok1 }, _ctx.ok1 ? { b: { 'ready': _o(_ctx.ready) } } : _ctx.ok2 ? {} : {}, { c: _ctx.ok2 })
}`
)
assert(
`<editor v-if="ok1" @ready="ready"/><editor v-else-if="ok2"/><editor v-else @ready="ready"/>`,
`<editor xhs:if="{{a}}" bindready="__e" data-e-o="{{b}}"/><editor xhs:elif="{{c}}"/><block xhs:else><editor xhs:if="{{r0}}" bindready="__e" data-e-o="{{d}}"/></block>`,
`(_ctx, _cache) => {
return _e({ a: _ctx.ok1 }, _ctx.ok1 ? { b: { 'ready': _o(_ctx.ready) } } : _ctx.ok2 ? {} : { d: { 'ready': _o(_ctx.ready) } }, { c: _ctx.ok2 })
}`
)
})
})
import { isMiniProgramNativeTag as isNativeTag } from '@dcloudio/uni-shared'
import { compile, CompilerOptions } from '@dcloudio/uni-mp-compiler'
import { compilerOptions, miniProgram } from '../src/compiler/options'
export function assert(
template: string,
templateCode: string,
renderCode: string,
options: CompilerOptions = {}
) {
const res = compile(template, {
mode: 'module',
filename: 'foo.vue',
prefixIdentifiers: true,
inline: true,
isNativeTag,
generatorOpts: {
concise: true,
},
miniProgram: {
...miniProgram,
emitFile({ source }) {
if (!options.onError) {
expect(source).toBe(templateCode)
}
return ''
},
},
...compilerOptions,
...options,
})
if (!options.onError) {
expect(res.code).toBe(renderCode)
}
}
import { assert } from './testUtils'
describe(`mp-xhs: transform v-for`, () => {
test(`with key`, () => {
assert(
`<view v-for="item in items" :key="item.id"/>`,
`<view xhs:for="{{a}}" xhs:for-item="item" xhs:key="a"/>`,
`(_ctx, _cache) => {
return { a: _f(_ctx.items, (item, k0, i0) => { return { a: item.id }; }) }
}`
)
})
test(`without key`, () => {
assert(
`<view v-for="item in items"/>`,
`<view xhs:for="{{a}}" xhs:for-item="item"/>`,
`(_ctx, _cache) => {
return { a: _f(_ctx.items, (item, k0, i0) => { return {}; }) }
}`
)
})
})
import { assert } from './testUtils'
describe(`mp-xhs: transform v-if`, () => {
test(`basic`, () => {
assert(
`<view v-if="ok"/><view v-else-if="ok1"/><view v-else/>`,
`<view xhs:if="{{a}}"/><view xhs:elif="{{b}}"/><view xhs:else/>`,
`(_ctx, _cache) => {
return _e({ a: _ctx.ok }, _ctx.ok ? {} : _ctx.ok1 ? {} : {}, { b: _ctx.ok1 })
}`
)
})
})
import { assert } from './testUtils'
describe('mp-xhs: transform v-model', () => {
test(`component v-model`, () => {
assert(
`<Comp v-model="model" />`,
`<comp xhs:if="{{b}}" u-i="2a9ec0b0-0" eO="{{a}}" bindupdateModelValue="__e" u-p="{{b}}"/>`,
`(_ctx, _cache) => {
return { a: _j({ 'updateModelValue': _o($event => _ctx.model = $event) }), b: _p({ modelValue: _ctx.model }) }
}`
)
})
test(`component v-model with cache`, () => {
assert(
`<Comp v-model="model" />`,
`<comp xhs:if="{{b}}" u-i="2a9ec0b0-0" eO="{{a}}" bindupdateModelValue="__e" u-p="{{b}}"/>`,
`(_ctx, _cache) => {
return { a: _j({ 'updateModelValue': _o($event => _ctx.model = $event) }), b: _p({ modelValue: _ctx.model }) }
}`,
{
cacheHandlers: true,
}
)
})
test(`input,textarea v-model`, () => {
assert(
`<input v-model="model" />`,
`<input value="{{a}}" bindinput="{{b}}"/>`,
`(_ctx, _cache) => {
return { a: _ctx.model, b: _o($event => _ctx.model = $event.detail.value) }
}`
)
assert(
`<textarea v-model="model" />`,
`<block xhs:if="{{r0}}"><textarea value="{{a}}" bindinput="{{b}}"/></block>`,
`(_ctx, _cache) => {
return { a: _ctx.model, b: _o($event => _ctx.model = $event.detail.value) }
}`
)
})
test(`input v-model + v-on`, () => {
assert(
`<input @input="input" v-model="model" />`,
`<input bindinput="__e" data-e-o="{{a}}" value="{{b}}"/>`,
`(_ctx, _cache) => {
return { a: { 'input': _o([$event => _ctx.model = $event.detail.value, _ctx.input]) }, b: _ctx.model }
}`
)
})
})
import { assert } from './testUtils'
describe('mp-xhs: transform v-on', () => {
describe('component', () => {
test(`built-in event`, () => {
assert(
`<custom @tap="tap"/>`,
`<custom bindtap="__e" u-i="2a9ec0b0-0" eO="{{a}}"/>`,
`(_ctx, _cache) => {
return { a: _j({ 'tap': _o(_ctx.tap) }) }
}`
)
})
test(`custom event`, () => {
assert(
`<custom @click="click"/>`,
`<custom bindclick="__e" u-i="2a9ec0b0-0" eO="{{a}}"/>`,
`(_ctx, _cache) => {
return { a: _j({ 'click': _o(_ctx.click) }) }
}`
)
}),
test(`multi custom event`, () => {
assert(
`<custom @unmount="unmount" @update:modelValue="changeHandle" @custom-mount="mount();created();"/>`,
`<custom bindunmount="__e" bindupdateModelValue="__e" bindcustomMount="__e" u-i="2a9ec0b0-0" eO="{{a}}"/>`,
`(_ctx, _cache) => {
return { a: _j({ 'unmount': _o(_ctx.unmount), 'updateModelValue': _o(_ctx.changeHandle), 'customMount': _o($event => { _ctx.mount(); _ctx.created(); }) }) }
}`
)
})
})
})
import { assert } from './testUtils'
describe('compiler: transform v-slot', () => {
test('default slot', () => {
assert(
`<custom><template v-slot/></custom>`,
`<custom u-s="{{['d']}}" u-i="2a9ec0b0-0"><view/></custom>`,
`(_ctx, _cache) => {
return {}
}`
)
assert(
`<custom>test</custom>`,
`<custom u-s="{{['d']}}" u-i="2a9ec0b0-0">test</custom>`,
`(_ctx, _cache) => {
return {}
}`
)
})
test('named slots', () => {
assert(
`<custom><template v-slot:header/><template v-slot:default/><template v-slot:footer/></custom>`,
`<custom u-s="{{['header','d','footer']}}" u-i="2a9ec0b0-0"><view slot="header"/><view/><view slot="footer"/></custom>`,
`(_ctx, _cache) => {
return {}
}`
)
assert(
`<unicloud-db v-slot:default="{data, loading, error, options}"><view v-if="error">{{error.message}}</view><view v-else></view></unicloud-db>`,
`<unicloud-db u-s="{{['d']}}" u-i="2a9ec0b0-0"><view><block xhs:for="{{a}}" xhs:for-item="v0" xhs:key="c"><view xhs:if="{{v0.a}}">{{v0.b}}</view><view xhs:else></view></block></view></unicloud-db>`,
`(_ctx, _cache) => {
return { a: _w(({ data, loading, error, options }, s0, i0) => { return _e({ a: error }, error ? { b: _t(error.message) } : {}, { c: i0 }); }, { name: 'd', path: 'a', vueId: '2a9ec0b0-0' }) }
}`
)
})
test('scoped slots', () => {
assert(
`<custom><template v-slot:default="slotProps"><view>{{ slotProps.item }}</view></template></custom>`,
`<custom u-s="{{['d']}}" u-i="2a9ec0b0-0"><view><block xhs:for="{{a}}" xhs:for-item="slotProps" xhs:key="b"><view>{{slotProps.a}}</view></block></view></custom>`,
`(_ctx, _cache) => {
return { a: _w((slotProps, s0, i0) => { return { a: _t(slotProps.item), b: i0 }; }, { name: 'd', path: 'a', vueId: '2a9ec0b0-0' }) }
}`
)
})
test('scoped slots + scoped slots', () => {
assert(
`<custom><template v-slot:default="slotProps"><custom1><template v-slot:default="slotProps1">{{ slotProps.item }}{{ slotProps1.item }}</template></custom1></template></custom>`,
`<custom u-s="{{['d']}}" u-i="2a9ec0b0-0"><view><block xhs:for="{{a}}" xhs:for-item="slotProps" xhs:key="d"><custom1 u-s="{{['d']}}" u-i="{{slotProps.c}}"><view><block xhs:for="{{slotProps.a}}" xhs:for-item="slotProps1" xhs:key="b">{{slotProps.b}}{{slotProps1.a}}</block></view></custom1></block></view></custom>`,
`(_ctx, _cache) => {
return { a: _w((slotProps, s0, i0) => { return { a: _w((slotProps1, s1, i1) => { return { a: _t(slotProps1.item), b: i1 }; }, { name: 'd', path: 'a[' + i0 + '].' + 'a', vueId: '2a9ec0b0-1' + '-' + i0 + ',' + '2a9ec0b0-0' }), b: _t(slotProps.item), c: '2a9ec0b0-1' + '-' + i0 + ',' + '2a9ec0b0-0', d: i0 }; }, { name: 'd', path: 'a', vueId: '2a9ec0b0-0' }) }
}`
)
})
test('v-if + scoped slots', () => {
assert(
`<custom><template v-if="ok" v-slot:default="slotProps"><view>{{ slotProps.item }}</view></template></custom>`,
`<custom u-s="{{['d']}}" u-i="2a9ec0b0-0"><view xhs:if="{{a}}"><block xhs:for="{{b}}" xhs:for-item="slotProps" xhs:key="b"><view>{{slotProps.a}}</view></block></view></custom>`,
`(_ctx, _cache) => {
return _e({ a: _ctx.ok }, _ctx.ok ? { b: _w((slotProps, s0, i0) => { return { a: _t(slotProps.item), b: i0 }; }, { name: 'd', path: 'b', vueId: '2a9ec0b0-0' }) } : {})
}`
)
})
test('v-for + scoped slots', () => {
assert(
`<custom v-for="item in items"><template v-slot:default="slotProps"><view>{{ slotProps.item }}</view></template></custom>`,
`<custom xhs:for="{{a}}" xhs:for-item="item" u-s="{{['d']}}" u-i="{{item.b}}"><view><block xhs:for="{{item.a}}" xhs:for-item="slotProps" xhs:key="b"><view>{{slotProps.a}}</view></block></view></custom>`,
`(_ctx, _cache) => {
return { a: _f(_ctx.items, (item, k0, i0) => { return { a: _w((slotProps, s1, i1) => { return { a: _t(slotProps.item), b: i1 }; }, { name: 'd', path: 'a[' + i0 + '].' + 'a', vueId: '2a9ec0b0-0' + '-' + i0 }), b: '2a9ec0b0-0' + '-' + i0 }; }) }
}`
)
})
test('v-for + v-for + scoped slots', () => {
assert(
`<view v-for="item in items"><custom v-for="item1 in item.list" :item="item1"><template v-slot:default="slotProps"><view>{{ slotProps.item }}</view></template></custom></view>`,
`<view xhs:for="{{a}}" xhs:for-item="item"><custom xhs:for="{{item.a}}" xhs:for-item="item1" u-s="{{['d']}}" u-i="{{item1.b}}" u-p="{{item1.c}}"><view><block xhs:for="{{item1.a}}" xhs:for-item="slotProps" xhs:key="b"><view>{{slotProps.a}}</view></block></view></custom></view>`,
`(_ctx, _cache) => {
return { a: _f(_ctx.items, (item, k0, i0) => { return { a: _f(item.list, (item1, k1, i1) => { return { a: _w((slotProps, s2, i2) => { return { a: _t(slotProps.item), b: i2 }; }, { name: 'd', path: 'a[' + i0 + '].' + ('a[' + i1 + '].') + 'a', vueId: '2a9ec0b0-0' + '-' + i0 + '-' + i1 }), b: '2a9ec0b0-0' + '-' + i0 + '-' + i1, c: _p({ item: item1 }) }; }) }; }) }
}`
)
})
test('old syntax', () => {
assert(
`<template slot="left"/>`,
`<view slot="left"/>`,
`(_ctx, _cache) => {
return {}
}`
)
})
})
[
{
"input": {
"src/compiler/index.ts": "dist/uni.compiler.js"
},
"output": {
"format": "cjs"
},
"external": [
"@vue/compiler-core",
"@dcloudio/uni-shared",
"@dcloudio/uni-cli-shared",
"@dcloudio/uni-mp-vite",
"@dcloudio/uni-mp-compiler"
]
},
{
"input": {
"src/runtime/index.ts": "dist/uni.mp.esm.js",
"src/api/index.ts": "dist/uni.api.esm.js"
},
"alias": {
"entries": [
{
"find": "@dcloudio/uni-platform",
"replacement": "packages/uni-mp-xhs/src/platform/index.ts"
},
{
"find": "@dcloudio/uni-mp-platform",
"replacement": "packages/uni-mp-core/src/platform/index.ts"
}
]
},
"replacements": {
"__GLOBAL__": "xhs",
"__PLATFORM__": "\"mp-xhs\"",
"__PLATFORM_TITLE__": "小红书小程序"
},
"external": [
"@dcloudio/uni-i18n",
"@dcloudio/uni-shared",
"@vue/shared",
"vue"
]
}
]
\ No newline at end of file
此差异已折叠。
'use strict';
var uniCliShared = require('@dcloudio/uni-cli-shared');
var initMiniProgramPlugin = require('@dcloudio/uni-mp-vite');
var path = require('path');
var uniMpCompiler = require('@dcloudio/uni-mp-compiler');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var initMiniProgramPlugin__default = /*#__PURE__*/_interopDefault(initMiniProgramPlugin);
var path__default = /*#__PURE__*/_interopDefault(path);
var description = "项目配置文件。";
var packOptions = {
ignore: [
]
};
var setting = {
urlCheck: false,
es6: true,
postcss: false,
minified: false,
newFeature: true,
bigPackageSizeSupport: true
};
var compileType = "miniprogram";
var libVersion = "";
var appid = "touristappid";
var projectname = "";
var condition = {
search: {
current: -1,
list: [
]
},
conversation: {
current: -1,
list: [
]
},
game: {
current: -1,
list: [
]
},
miniprogram: {
current: -1,
list: [
]
}
};
var source = {
description: description,
packOptions: packOptions,
setting: setting,
compileType: compileType,
libVersion: libVersion,
appid: appid,
projectname: projectname,
condition: condition
};
/**
* 小红书小程序的Page和自定义组件,不支持动态事件绑定,需要通过__e转发
*/
const transformOn = uniCliShared.createTransformOn(uniMpCompiler.transformOn, {
match: (name, node, context) => {
return true;
},
});
/**
* 小红书小程序的自定义组件,不支持动态事件绑定,故 v-model 也需要调整
*/
const transformModel = uniCliShared.createTransformModel(uniMpCompiler.transformModel);
const directiveTransforms = {
on: transformOn,
model: transformModel,
};
const compilerOptions = {
nodeTransforms: [
uniCliShared.transformRef,
// transformComponentLink,
uniCliShared.transformMatchMedia,
],
directiveTransforms,
};
const COMPONENTS_DIR = 'xhscomponents';
const miniProgram = {
class: {
array: false,
},
slot: {
fallbackContent: false,
dynamicSlotNames: false,
},
event: {
key: true,
},
directive: 'xhs:',
lazyElement: {
canvas: [
{ name: 'bind', arg: ['canvas-id', 'id'] },
{
name: 'on',
arg: ['touchstart', 'touchmove', 'touchcancel', 'touchend'],
},
],
editor: [
{
name: 'on',
arg: ['ready'],
},
],
'scroll-view': [
{
name: 'on',
arg: ['dragstart', 'dragging', 'dragend'],
},
],
// iOS 平台需要延迟
input: [{ name: 'bind', arg: ['type'] }],
textarea: [{ name: 'on', arg: ['input'] }],
},
component: {
dir: COMPONENTS_DIR,
},
};
const projectConfigFilename = 'project.config.json';
const options = {
cdn: 3,
vite: {
inject: {
uni: [path__default.default.resolve(__dirname, 'uni.api.esm.js'), 'default'],
},
alias: {
'uni-mp-runtime': path__default.default.resolve(__dirname, 'uni.mp.esm.js'),
},
copyOptions: {
assets: [COMPONENTS_DIR],
targets: [
// ...(process.env.UNI_MP_PLUGIN ? [copyMiniProgramPluginJson] : []),
{
src: [
'sitemap.json',
'project.private.config.json',
projectConfigFilename,
],
get dest() {
return process.env.UNI_OUTPUT_DIR;
},
},
// ...copyMiniProgramThemeJson(),
],
},
},
global: 'xhs',
app: {
darkmode: false,
subpackages: true,
usingComponents: true,
},
project: {
filename: projectConfigFilename,
config: ['project.config.json'],
source,
},
template: Object.assign(Object.assign({}, miniProgram), { filter:
// undefined,
{
extname: '.sjs',
lang: 'sjs',
generate(filter, filename) {
if (filename) {
return `<import-sjs src="${filename}.sjs" module="${filter.name}"/>`;
}
return `<import-sjs module="${filter.name}">
${filter.code}
</import-sjs>`;
},
}, extname: '.xhsml', compilerOptions }),
style: {
extname: '.css',
},
};
const uniMiniProgramXhsPlugin = {
name: 'uni:mp-xhs',
config() {
return {
define: {
__VUE_CREATED_DEFERRED__: false,
},
build: {
// 图片资源转行内base64最大size限制
assetsInlineLimit: uniCliShared.ASSETS_INLINE_LIMIT,
},
};
},
};
var index = [uniMiniProgramXhsPlugin, ...initMiniProgramPlugin__default.default(options)];
module.exports = index;
此差异已折叠。
{
"name": "@dcloudio/uni-mp-xhs",
"version": "3.0.0-alpha-3071220230324001",
"description": "uniapp mp-xhs",
"main": "dist/index.js",
"files": [
"dist",
"lib"
],
"repository": {
"type": "git",
"url": "git+https://github.com/dcloudio/uni-app.git",
"directory": "packages/uni-mp-xhs"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "Apache-2.0",
"uni-app": {
"name": "mp-xhs",
"title": "小红书小程序",
"apply": [
"mp-xhs"
],
"main": "dist/uni.compiler.js"
},
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
"devDependencies": {
"@dcloudio/uni-mp-weixin": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-mp-alipay": "3.0.0-alpha-3071220230324001",
"@vue/compiler-core": "3.2.47"
},
"dependencies": {
"@dcloudio/uni-cli-shared": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-mp-compiler": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-mp-vite": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-mp-vue": "3.0.0-alpha-3071220230324001",
"@dcloudio/uni-shared": "3.0.0-alpha-3071220230324001",
"@vue/shared": "3.2.47"
}
}
import { initUni } from '@dcloudio/uni-mp-core'
import * as shims from './shims'
import * as protocols from './protocols'
export default initUni(shims, protocols)
import {
redirectTo,
navigateTo,
previewImage,
getSystemInfo,
getSystemInfoSync,
} from '@dcloudio/uni-mp-core'
export {
redirectTo,
navigateTo,
previewImage,
getSystemInfo,
getSystemInfoSync,
}
import { initGetProvider } from '@dcloudio/uni-mp-core'
export const getProvider = initGetProvider({
oauth: ['xhs'],
share: ['xhs'],
payment: ['xhs'],
push: ['xhs'],
})
import type { Plugin } from 'vite'
import { ASSETS_INLINE_LIMIT } from '@dcloudio/uni-cli-shared'
import initMiniProgramPlugin from '@dcloudio/uni-mp-vite'
import { options } from './options'
const uniMiniProgramXhsPlugin: Plugin = {
name: 'uni:mp-xhs',
config() {
return {
define: {
__VUE_CREATED_DEFERRED__: false,
},
build: {
// 图片资源转行内base64最大size限制
assetsInlineLimit: ASSETS_INLINE_LIMIT,
},
}
},
}
export default [uniMiniProgramXhsPlugin, ...initMiniProgramPlugin(options)]
import path from 'path'
import type { CompilerOptions } from '@vue/compiler-core'
import {
// COMPONENT_CUSTOM_HIDDEN,
// copyMiniProgramPluginJson,
// copyMiniProgramThemeJson,
MiniProgramCompilerOptions,
// transformComponentLink,
transformMatchMedia,
transformRef,
} from '@dcloudio/uni-cli-shared'
import { UniMiniProgramPluginOptions } from '@dcloudio/uni-mp-vite'
import source from './project.config.json'
import { transformOn } from './transforms/vOn'
import { transformModel } from './transforms/vModel'
const directiveTransforms = {
on: transformOn,
model: transformModel,
}
export const compilerOptions: CompilerOptions = {
nodeTransforms: [
transformRef,
// transformComponentLink,
transformMatchMedia,
],
directiveTransforms,
}
const COMPONENTS_DIR = 'xhscomponents'
export const miniProgram: MiniProgramCompilerOptions = {
class: {
array: false,
},
slot: {
fallbackContent: false,
dynamicSlotNames: false,
},
event: {
key: true,
},
directive: 'xhs:',
lazyElement: {
canvas: [
{ name: 'bind', arg: ['canvas-id', 'id'] },
{
name: 'on',
arg: ['touchstart', 'touchmove', 'touchcancel', 'touchend'],
},
],
editor: [
{
name: 'on',
arg: ['ready'],
},
],
'scroll-view': [
{
name: 'on',
arg: ['dragstart', 'dragging', 'dragend'],
},
],
// iOS 平台需要延迟
input: [{ name: 'bind', arg: ['type'] }],
textarea: [{ name: 'on', arg: ['input'] }],
},
component: {
dir: COMPONENTS_DIR,
},
}
const projectConfigFilename = 'project.config.json'
export const options: UniMiniProgramPluginOptions = {
cdn: 3,
vite: {
inject: {
uni: [path.resolve(__dirname, 'uni.api.esm.js'), 'default'],
},
alias: {
'uni-mp-runtime': path.resolve(__dirname, 'uni.mp.esm.js'),
},
copyOptions: {
assets: [COMPONENTS_DIR],
targets: [
// ...(process.env.UNI_MP_PLUGIN ? [copyMiniProgramPluginJson] : []),
{
src: [
'sitemap.json',
'project.private.config.json',
projectConfigFilename,
],
get dest() {
return process.env.UNI_OUTPUT_DIR
},
},
// ...copyMiniProgramThemeJson(),
],
},
},
global: 'xhs',
app: {
darkmode: false,
subpackages: true,
usingComponents: true,
},
project: {
filename: projectConfigFilename,
config: ['project.config.json'],
source,
},
template: {
/* eslint-disable no-restricted-syntax */
...miniProgram,
filter:
// undefined,
{
extname: '.sjs',
lang: 'sjs',
generate(filter, filename) {
if (filename) {
return `<import-sjs src="${filename}.sjs" module="${filter.name}"/>`
}
return `<import-sjs module="${filter.name}">
${filter.code}
</import-sjs>`
},
},
extname: '.xhsml',
compilerOptions,
},
style: {
extname: '.css',
},
}
{
"description": "项目配置文件。",
"packOptions": {
"ignore": []
},
"setting": {
"urlCheck": false,
"es6": true,
"postcss": false,
"minified": false,
"newFeature": true,
"bigPackageSizeSupport": true
},
"compileType": "miniprogram",
"libVersion": "",
"appid": "touristappid",
"projectname": "",
"condition": {
"search": {
"current": -1,
"list": []
},
"conversation": {
"current": -1,
"list": []
},
"game": {
"current": -1,
"list": []
},
"miniprogram": {
"current": -1,
"list": []
}
}
}
\ No newline at end of file
import { createTransformModel } from '@dcloudio/uni-cli-shared'
import { transformModel as baseTransformModel } from '@dcloudio/uni-mp-compiler'
/**
* 小红书小程序的自定义组件,不支持动态事件绑定,故 v-model 也需要调整
*/
export const transformModel = createTransformModel(baseTransformModel)
import { createTransformOn } from '@dcloudio/uni-cli-shared'
import { transformOn as baseTransformOn } from '@dcloudio/uni-mp-compiler'
/**
* 小红书小程序的Page和自定义组件,不支持动态事件绑定,需要通过__e转发
*/
export const transformOn = createTransformOn(baseTransformOn, {
match: (name, node, context) => {
return true
},
})
export function getBaseSystemInfo() {
return xhs.getSystemInfoSync()
}
import {
ComponentOptions,
// @ts-ignore
devtoolsComponentAdded,
} from 'vue'
import {
PAGE_INIT_HOOKS,
initData,
initHooks,
initUnknownHooks,
$destroyComponent,
initWxsCallMethods,
initRuntimeHooks,
handleEvent,
} from '@dcloudio/uni-mp-core'
import {
addLeadingSlash,
ON_LOAD,
ON_SHOW,
ON_READY,
ON_UNLOAD,
stringifyQuery,
} from '@dcloudio/uni-shared'
import {
handleRef,
handleLink,
initSpecialMethods,
createVueComponent,
} from './util'
import { extend, isPlainObject } from '@vue/shared'
declare function Page<D>(options: tinyapp.PageOptions<D>): void
export function initCreatePage() {
return function createPage(vueOptions: ComponentOptions) {
vueOptions = vueOptions.default || vueOptions
const pageOptions: tinyapp.PageOptions = {
onLoad(query) {
this.options = query
this.$page = {
fullPath: addLeadingSlash(this.route + stringifyQuery(query)),
}
// 初始化 vue 实例
this.props = query
this.$vm = createVueComponent('page', this, vueOptions)
initSpecialMethods(this)
this.$vm.$callHook(ON_LOAD, query)
},
onShow() {
if (__VUE_PROD_DEVTOOLS__) {
devtoolsComponentAdded(this.$vm.$)
}
this.$vm.$callHook(ON_SHOW)
},
onReady() {
this.$vm.$callHook('mounted')
this.$vm.$callHook(ON_READY)
},
onUnload() {
if (this.$vm) {
this.$vm.$callHook(ON_UNLOAD)
$destroyComponent(this.$vm)
}
},
__r: handleRef,
__l: handleLink,
__e: function (event: any) {
const {
currentTarget: { dataset },
} = event
dataset['eO'] = {
// eslint-disable-next-line no-restricted-syntax
...dataset['eO'],
tap: dataset['eO']?.tap || dataset['eO']?.click,
}
// console.log('触发了page事件', event)
// @ts-ignore
return handleEvent.call(this, event)
},
}
if (isPlainObject(vueOptions.events)) {
extend(pageOptions.events!, vueOptions.events)
}
if (__VUE_OPTIONS_API__) {
pageOptions.data = initData(vueOptions)
}
initHooks(pageOptions, PAGE_INIT_HOOKS)
initUnknownHooks(pageOptions, vueOptions)
initRuntimeHooks(pageOptions, vueOptions.__runtimeHooks)
initWxsCallMethods(
pageOptions as WechatMiniprogram.Component.MethodOption,
vueOptions.wxsCallMethods
)
return Page(pageOptions)
}
}
import { EventChannel } from '@dcloudio/uni-shared'
import {
initCreateApp,
initCreateComponent,
initCreateSubpackageApp,
} from '@dcloudio/uni-mp-core'
import '@dcloudio/uni-mp-polyfill'
import { initCreatePage } from './createPage'
import * as parseComponentOptions from './parseComponentOptions'
export const createApp = initCreateApp()
export const createPage = initCreatePage()
export const createComponent = initCreateComponent(parseComponentOptions)
export const createSubpackageApp = initCreateSubpackageApp()
;(xhs as any).EventChannel = EventChannel
;(xhs as any).createApp = (global as any).createApp = createApp
;(xhs as any).createPage = createPage
;(xhs as any).createComponent = createComponent
;(xhs as any).createSubpackageApp = (global as any).createSubpackageApp =
createSubpackageApp
import {
MPComponentInstance,
MPComponentOptions,
handleEvent,
} from '@dcloudio/uni-mp-core'
// import { handleLink } from '@dcloudio/uni-mp-weixin'
export { handleLink, initLifetimes } from '@dcloudio/uni-mp-weixin'
export const mocks = ['nodeId', 'componentPath', 'componentId']
export function isPage(mpInstance: MPComponentInstance) {
return !!mpInstance.route
}
export function initRelation(
mpInstance: MPComponentInstance,
detail: Record<string, unknown>
) {
// 小红书自定义组件从customEventMap取事件名
mpInstance.customEventMap = {
// @ts-ignore
__l: '__l',
}
mpInstance.triggerEvent('__l', detail)
}
export function parse(componentOptions: MPComponentOptions) {
const methods = componentOptions.methods as Record<
string,
(...args: any[]) => any
>
methods.__e = function (event: any) {
const {
currentTarget: { dataset },
} = event
dataset['eO'] = {
// eslint-disable-next-line no-restricted-syntax
...dataset['eO'],
tap: dataset['eO']?.tap || dataset['eO']?.click,
}
// console.log('触发了component事件', event)
// @ts-ignore
return handleEvent.call(this, event)
}
}
import { hasOwn, isFunction, isString } from '@vue/shared'
import {
ComponentPublicInstance,
ComponentOptions,
ComponentInternalInstance,
isRef,
Ref,
} from 'vue'
// @ts-ignore EMPTY_OBJ 不能从 @vue/shared 中引入,从 vue 中导入,保持一致
import { EMPTY_OBJ, setTemplateRef } from 'vue'
import {
initMocks,
$createComponent,
initComponentInstance,
CreateComponentOptions,
findPropsData,
initRefs,
} from '@dcloudio/uni-mp-core'
export { handleLink } from '@dcloudio/uni-mp-weixin'
type MPPageInstance = tinyapp.IPageInstance<Record<string, any>>
export type MPComponentInstance = tinyapp.IComponentInstance<
Record<string, any>,
any
>
export const isComponent2 = xhs.canIUse('component2')
export const mocks = ['nodeId', 'componentId', 'componentPath']
export function initSpecialMethods(
mpInstance: MPPageInstance | MPComponentInstance
) {
if (!mpInstance.$vm) {
return
}
let path = mpInstance.is || mpInstance.route
if (!path) {
return
}
if (path.indexOf('/') === 0) {
path = path.slice(1)
}
const specialMethods =
(xhs as any).specialMethods && (xhs as any).specialMethods[path]
if (specialMethods) {
specialMethods.forEach((method: string) => {
if (isFunction(mpInstance.$vm[method])) {
mpInstance[method] = function (event: Record<string, any>) {
if (hasOwn(event, 'markerId')) {
event.detail = typeof event.detail === 'object' ? event.detail : {}
event.detail.markerId = event.markerId
}
// TODO normalizeEvent
mpInstance.$vm[method](event)
}
}
})
}
}
export function handleRef(this: MPComponentInstance, ref: MPComponentInstance) {
if (!ref) {
return
}
const refName = ref.props.uR // data-ref
const refInForName = ref.props.uRIF // data-ref-in-for
if (!refName && !refInForName) {
return
}
const instance = this.$vm.$
const refs =
instance.refs === EMPTY_OBJ ? (instance.refs = {}) : instance.refs
const { setupState } = instance
const refValue = ref.$vm
if (refName) {
if (isString(refName)) {
refs[refName] = refValue
if (hasOwn(setupState, refName)) {
setupState[refName] = refValue
}
} else {
setRef(refName, refValue, refs, setupState)
}
} else if (refInForName) {
if (isString(refInForName)) {
;(refs[refInForName] || (refs[refInForName] = [])).push(refValue)
} else {
setRef(refInForName, refValue, refs, setupState)
}
}
}
type VNodeRef =
| string
| Ref
| ((ref: object | null, refs: Record<string, any>) => void)
type TemplateRef = {
r: VNodeRef
k?: string // setup ref key
f?: boolean // refInFor marker
}
function isTemplateRef(opts: unknown): opts is TemplateRef {
return !!(opts && (opts as TemplateRef).r)
}
function setRef(
ref: Ref | ((ref: object | null, refs: Record<string, any>) => void),
refValue: ComponentPublicInstance,
refs: Record<string, unknown>,
setupState: Data
) {
if (isRef(ref)) {
ref.value = refValue
} else if (isFunction(ref)) {
const templateRef = ref(refValue, refs)
if (isTemplateRef(templateRef)) {
setTemplateRef(templateRef, refValue, setupState)
}
}
}
export function createVueComponent(
mpType: 'page' | 'component',
mpInstance: MPPageInstance | MPComponentInstance,
vueOptions: ComponentOptions,
parent?: ComponentPublicInstance
) {
return $createComponent(
{
type: vueOptions,
props: findPropsData(mpInstance.props, mpType === 'page'),
},
{
mpType,
mpInstance,
slots: mpInstance.props.uS || {}, // vueSlots
parentComponent: parent && parent.$,
onBeforeSetup(
instance: ComponentInternalInstance,
options: CreateComponentOptions
) {
initRefs(instance, mpInstance as any)
initMocks(instance, mpInstance as any, mocks)
initComponentInstance(instance, options)
},
}
) as ComponentPublicInstance
}
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"paths": {
"@dcloudio/*": ["packages/*/src"],
"@dcloudio/uni-platform": [
"packages/uni-mp-xhs/src/platform/index.ts"
],
"@dcloudio/uni-mp-polyfill": ["packages/uni-mp-core/src/runtime/polyfill"]
}
}
}
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册