From 3193659db71de1c1788253453b028ddc91424d8c Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Mon, 25 Oct 2021 14:38:56 +0800 Subject: [PATCH] wip(mp): easycom --- packages/uni-cli-shared/src/exports.ts | 1 + packages/uni-cli-shared/src/index.ts | 1 + .../src/plugin/configureServer/index.ts | 24 ++++ .../configureServer/middlewares/static.ts | 4 +- .../configureServer/middlewares/timestamp.ts | 39 ++++++ .../src/plugin/configureServer/ssr.ts | 39 ++++++ .../src/plugin}/configureServer/static.ts | 26 ++-- packages/uni-h5-vite/src/plugin/index.ts | 78 +----------- packages/uni-mp-vue/dist/vue.runtime.esm.js | 116 ++++++++++-------- packages/uni-mp-vue/lib/vue.runtime.esm.js | 19 +-- packages/uni-mp-vue/src/helpers/index.ts | 35 +++++- packages/uni-mp-vue/src/helpers/vFor.ts | 2 +- packages/uni-mp-vue/src/index.ts | 16 +-- packages/vite-plugin-uni/src/cli/action.ts | 7 +- packages/vite-plugin-uni/src/cli/server.ts | 8 +- packages/vite-plugin-uni/src/cli/utils.ts | 3 + packages/vite-plugin-uni/src/config/build.ts | 2 +- .../src/configureServer/easycom.ts | 26 ---- .../src/configureServer/index.ts | 16 --- packages/vite-plugin-uni/src/index.ts | 2 - packages/vite-plugin-uni/src/utils/easycom.ts | 32 +++++ 21 files changed, 284 insertions(+), 212 deletions(-) create mode 100644 packages/uni-cli-shared/src/exports.ts create mode 100644 packages/uni-h5-vite/src/plugin/configureServer/index.ts rename packages/{vite-plugin-uni/src => uni-h5-vite/src/plugin}/configureServer/middlewares/static.ts (96%) create mode 100644 packages/uni-h5-vite/src/plugin/configureServer/middlewares/timestamp.ts create mode 100644 packages/uni-h5-vite/src/plugin/configureServer/ssr.ts rename packages/{vite-plugin-uni/src => uni-h5-vite/src/plugin}/configureServer/static.ts (60%) delete mode 100644 packages/vite-plugin-uni/src/configureServer/easycom.ts delete mode 100644 packages/vite-plugin-uni/src/configureServer/index.ts create mode 100644 packages/vite-plugin-uni/src/utils/easycom.ts diff --git a/packages/uni-cli-shared/src/exports.ts b/packages/uni-cli-shared/src/exports.ts new file mode 100644 index 000000000..1fff44f8e --- /dev/null +++ b/packages/uni-cli-shared/src/exports.ts @@ -0,0 +1 @@ +export { default as chokidar } from 'chokidar' diff --git a/packages/uni-cli-shared/src/index.ts b/packages/uni-cli-shared/src/index.ts index 5a9ce5263..d26584a44 100644 --- a/packages/uni-cli-shared/src/index.ts +++ b/packages/uni-cli-shared/src/index.ts @@ -17,4 +17,5 @@ export * from './filter' export * from './esbuild' export { M } from './messages' +export * from './exports' export { checkUpdate } from './checkUpdate' diff --git a/packages/uni-h5-vite/src/plugin/configureServer/index.ts b/packages/uni-h5-vite/src/plugin/configureServer/index.ts new file mode 100644 index 000000000..76411ddb4 --- /dev/null +++ b/packages/uni-h5-vite/src/plugin/configureServer/index.ts @@ -0,0 +1,24 @@ +import { + getRouterOptions, + parseManifestJsonOnce, +} from '@dcloudio/uni-cli-shared' +import { Plugin } from 'vite' +import { uniTimestampMiddleware } from './middlewares/timestamp' +import { initSSR } from './ssr' +import { initStatic } from './static' + +export function createConfigureServer(): Plugin['configureServer'] { + return function (server) { + initSSR(server) + + const routerOptions = getRouterOptions( + parseManifestJsonOnce(process.env.UNI_INPUT_DIR) + ) + if (routerOptions.mode === 'history') { + server.middlewares.use(uniTimestampMiddleware(server)) + } + return () => { + initStatic(server) + } + } +} diff --git a/packages/vite-plugin-uni/src/configureServer/middlewares/static.ts b/packages/uni-h5-vite/src/plugin/configureServer/middlewares/static.ts similarity index 96% rename from packages/vite-plugin-uni/src/configureServer/middlewares/static.ts rename to packages/uni-h5-vite/src/plugin/configureServer/middlewares/static.ts index 20348ebc6..df835f98c 100644 --- a/packages/vite-plugin-uni/src/configureServer/middlewares/static.ts +++ b/packages/uni-h5-vite/src/plugin/configureServer/middlewares/static.ts @@ -69,11 +69,11 @@ interface UniStaticMiddlewareOptions { resolve: (pathname: string) => string | void } -type NextHandler = () => void | Promise +export type NextHandler = () => void | Promise export function uniStaticMiddleware(opts: UniStaticMiddlewareOptions) { const isEtag = !!opts.etag - return function ( + return function staticMiddleware( req: IncomingMessage, res: ServerResponse, next: NextHandler diff --git a/packages/uni-h5-vite/src/plugin/configureServer/middlewares/timestamp.ts b/packages/uni-h5-vite/src/plugin/configureServer/middlewares/timestamp.ts new file mode 100644 index 000000000..823febb66 --- /dev/null +++ b/packages/uni-h5-vite/src/plugin/configureServer/middlewares/timestamp.ts @@ -0,0 +1,39 @@ +import { parse as parseUrl } from 'url' +import { IncomingMessage, ServerResponse } from 'http' +import { ViteDevServer } from 'vite' +import { NextHandler } from './static' +import path from 'path' +import { EXTNAME_VUE_RE } from '@dcloudio/uni-cli-shared' + +export function uniTimestampMiddleware(server: ViteDevServer) { + return async function timestampMiddleware( + req: IncomingMessage, + _: ServerResponse, + next: NextHandler + ) { + // 当页面被作为组件引用时,会导致history刷新该页面直接显示js代码,因为该页面已被缓存为了module, + // https://github.com/vitejs/vite/blob/702d50315535c189151c67d33e4a22124f926bed/packages/vite/src/node/server/transformRequest.ts#L52 + // /pages/tabBar/API/API + let { url } = req + if (url) { + const base = server.config.base + const parsed = parseUrl(url) + let newUrl = url + if ((parsed.pathname || '/').startsWith(base)) { + newUrl = newUrl.replace(base, '/') + } + if ( + !path.extname(newUrl) && + !newUrl.endsWith('/') && + !newUrl.includes('?') + ) { + const module = await server.moduleGraph.getModuleByUrl(newUrl) + if (module && module.file && EXTNAME_VUE_RE.test(module.file)) { + // /pages/tabBar/API/API => /pages/tabBar/API/API?__t__=time + req.url = url + '?__t__=' + Date.now() + } + } + } + next() + } +} diff --git a/packages/uni-h5-vite/src/plugin/configureServer/ssr.ts b/packages/uni-h5-vite/src/plugin/configureServer/ssr.ts new file mode 100644 index 000000000..a7b636cc1 --- /dev/null +++ b/packages/uni-h5-vite/src/plugin/configureServer/ssr.ts @@ -0,0 +1,39 @@ +import { ViteDevServer } from 'vite' + +export const external = [ + '@dcloudio/uni-app', + '@dcloudio/uni-cloud', + '@dcloudio/uni-h5', + '@dcloudio/uni-h5-vue', + '@dcloudio/uni-i18n', + '@dcloudio/uni-shared', + '@dcloudio/uni-stat', + '@vue/shared', + 'vue', + 'vue-i18n', + 'vue-router', + 'vuex', +] + +export function initSSR(server: ViteDevServer) { + const { ssrLoadModule } = server + let added = false + server.ssrLoadModule = (url) => { + const res = ssrLoadModule(url) + if (!added) { + // HBuilderX项目,根目录可能没有package.json,导致 ssrExternals 不生效 + added = true + if ((server as any)._ssrExternals) { + const { _ssrExternals } = server as unknown as { + _ssrExternals: string[] + } + external.forEach((module) => { + if (!_ssrExternals.includes(module)) { + _ssrExternals.push(module) + } + }) + } + } + return res + } +} diff --git a/packages/vite-plugin-uni/src/configureServer/static.ts b/packages/uni-h5-vite/src/plugin/configureServer/static.ts similarity index 60% rename from packages/vite-plugin-uni/src/configureServer/static.ts rename to packages/uni-h5-vite/src/plugin/configureServer/static.ts index 8b9221aad..bfd788370 100644 --- a/packages/vite-plugin-uni/src/configureServer/static.ts +++ b/packages/uni-h5-vite/src/plugin/configureServer/static.ts @@ -2,13 +2,14 @@ import fs from 'fs' import path from 'path' import debug from 'debug' import { ViteDevServer } from 'vite' - -import { isImportRequest } from '@dcloudio/uni-cli-shared' - -import { VitePluginUniResolvedOptions } from '..' +import { createFilter } from '@rollup/pluginutils' +import { + isImportRequest, + normalizePath, + PUBLIC_DIR, +} from '@dcloudio/uni-cli-shared' import { uniStaticMiddleware } from './middlewares/static' -import { createPublicFileFilter } from '../utils' const debugStatic = debug('vite:uni:static') /** @@ -16,10 +17,7 @@ const debugStatic = debug('vite:uni:static') * @param server * @param param */ -export const serveStatic = ( - server: ViteDevServer, - { inputDir }: VitePluginUniResolvedOptions -) => { +export const initStatic = (server: ViteDevServer) => { const filter = createPublicFileFilter() const serve = uniStaticMiddleware({ etag: true, @@ -27,7 +25,7 @@ export const serveStatic = ( if (!filter(pathname)) { return } - const filename = path.join(inputDir, pathname) + const filename = path.join(process.env.UNI_INPUT_DIR, pathname) if (fs.existsSync(filename)) { debugStatic(filename, 'success') return filename @@ -44,3 +42,11 @@ export const serveStatic = ( return serve(req, res, next) }) } + +export function createPublicFileFilter(base: string = '/') { + const publicDir = normalizePath(path.join(base, PUBLIC_DIR + '/**/*')) + const uniModulesDir = normalizePath( + path.join(base, 'uni_modules/*/' + PUBLIC_DIR + '/**/*') + ) + return createFilter([publicDir, uniModulesDir]) +} diff --git a/packages/uni-h5-vite/src/plugin/index.ts b/packages/uni-h5-vite/src/plugin/index.ts index 92bfb0b72..0448e836f 100644 --- a/packages/uni-h5-vite/src/plugin/index.ts +++ b/packages/uni-h5-vite/src/plugin/index.ts @@ -1,36 +1,18 @@ import fs from 'fs' import path from 'path' -import { parse as parseUrl } from 'url' +import { isH5CustomElement, isH5NativeTag } from '@dcloudio/uni-shared' import { isInHBuilderX, resolveMainPathOnce, UniVitePlugin, - getRouterOptions, - parseManifestJsonOnce, - EXTNAME_VUE_RE, } from '@dcloudio/uni-cli-shared' import { createHandleHotUpdate } from './handleHotUpdate' import { createTransformIndexHtml } from './transformIndexHtml' import { createDefine } from '../utils/features' import { isSsr } from '../utils' -import { ViteDevServer } from 'vite' import { esbuildPrePlugin } from './esbuild/esbuildPrePlugin' -import { isH5CustomElement, isH5NativeTag } from '@dcloudio/uni-shared' - -const external = [ - '@dcloudio/uni-app', - '@dcloudio/uni-cloud', - '@dcloudio/uni-h5', - '@dcloudio/uni-h5-vue', - '@dcloudio/uni-i18n', - '@dcloudio/uni-shared', - '@dcloudio/uni-stat', - '@vue/shared', - 'vue', - 'vue-i18n', - 'vue-router', - 'vuex', -] +import { external } from './configureServer/ssr' +import { createConfigureServer } from './configureServer' export const UniH5Plugin: UniVitePlugin = { name: 'vite:uni-h5', @@ -85,59 +67,7 @@ export const UniH5Plugin: UniVitePlugin = { // TODO 禁止 optimizeDeps ;(config as any).cacheDir = '' }, - configureServer(server: ViteDevServer) { - const { ssrLoadModule } = server - let added = false - server.ssrLoadModule = (url) => { - const res = ssrLoadModule(url) - if (!added) { - // HBuilderX项目,根目录可能没有package.json,导致 ssrExternals 不生效 - added = true - if ((server as any)._ssrExternals) { - const { _ssrExternals } = server as unknown as { - _ssrExternals: string[] - } - external.forEach((module) => { - if (!_ssrExternals.includes(module)) { - _ssrExternals.push(module) - } - }) - } - } - return res - } - const routerOptions = getRouterOptions( - parseManifestJsonOnce(process.env.UNI_INPUT_DIR) - ) - if (routerOptions.mode === 'history') { - server.middlewares.use(async (req, res, next) => { - // 当页面被作为组件引用时,会导致history刷新该页面直接显示js代码,因为该页面已被缓存为了module, - // https://github.com/vitejs/vite/blob/702d50315535c189151c67d33e4a22124f926bed/packages/vite/src/node/server/transformRequest.ts#L52 - // /pages/tabBar/API/API - let { url } = req - if (url) { - const base = server.config.base - const parsed = parseUrl(url) - let newUrl = url - if ((parsed.pathname || '/').startsWith(base)) { - newUrl = newUrl.replace(base, '/') - } - if ( - !path.extname(newUrl) && - !newUrl.endsWith('/') && - !newUrl.includes('?') - ) { - const module = await server.moduleGraph.getModuleByUrl(newUrl) - if (module && module.file && EXTNAME_VUE_RE.test(module.file)) { - // /pages/tabBar/API/API => /pages/tabBar/API/API?__t__=time - req.url = url + '?__t__=' + Date.now() - } - } - } - next() - }) - } - }, + configureServer: createConfigureServer(), handleHotUpdate: createHandleHotUpdate(), transformIndexHtml: createTransformIndexHtml(), } diff --git a/packages/uni-mp-vue/dist/vue.runtime.esm.js b/packages/uni-mp-vue/dist/vue.runtime.esm.js index 094fe06c8..c583ecb81 100644 --- a/packages/uni-mp-vue/dist/vue.runtime.esm.js +++ b/packages/uni-mp-vue/dist/vue.runtime.esm.js @@ -1,5 +1,5 @@ -import { extend, isSymbol, isObject, toRawType, def, hasChanged, isArray, isFunction, NOOP, remove, toHandlerKey, camelize, capitalize, isString, normalizeClass, normalizeStyle, isOn, isPromise, EMPTY_OBJ, isSet, isMap, isPlainObject, toTypeString, invokeArrayFns, hasOwn, NO, isIntegerKey, toNumber, hyphenate, isReservedProp, EMPTY_ARR, makeMap, stringifyStyle as stringifyStyle$1 } from '@vue/shared'; -export { camelize as c, camelize, extend as e, hyphenate as h, normalizeClass as n, normalizeClass, normalizeProps, normalizeStyle, toDisplayString as t, toDisplayString, toHandlerKey } from '@vue/shared'; +import { extend, isSymbol, isObject, toRawType, def, hasChanged, isArray, isFunction, NOOP, remove, toHandlerKey, camelize, capitalize, isString, normalizeClass, normalizeStyle, isOn, isPromise, EMPTY_OBJ, isSet, isMap, isPlainObject, toTypeString, invokeArrayFns, hasOwn, NO, isIntegerKey, toNumber, hyphenate, isReservedProp, EMPTY_ARR, makeMap, stringifyStyle as stringifyStyle$1, toDisplayString } from '@vue/shared'; +export { camelize, normalizeClass, normalizeProps, normalizeStyle, toDisplayString, toHandlerKey } from '@vue/shared'; import { isRootHook, ON_ERROR, UniLifecycleHooks } from '@dcloudio/uni-shared'; function warn(msg, ...args) { @@ -4290,6 +4290,9 @@ const version = "3.2.20"; */ const resolveFilter = null; +function unwrapper(target) { + return toRaw(unref(target)); +} // import deepCopy from './deepCopy' /** * https://raw.githubusercontent.com/Tencent/westore/master/packages/westore/utils/diff.js @@ -4304,7 +4307,7 @@ function diff(current, pre) { return result; } function syncKeys(current, pre) { - current = unref(current); + current = unwrapper(current); if (current === pre) return; const rootCurrentType = toTypeString(current); @@ -4329,7 +4332,7 @@ function syncKeys(current, pre) { } } function _diff(current, pre, path, result) { - current = unref(current); + current = unwrapper(current); if (current === pre) return; const rootCurrentType = toTypeString(current); @@ -4341,7 +4344,7 @@ function _diff(current, pre, path, result) { } else { for (let key in current) { - const currentValue = unref(current[key]); + const currentValue = unwrapper(current[key]); const preValue = pre[key]; const currentType = toTypeString(currentValue); const preType = toTypeString(preValue); @@ -4483,10 +4486,10 @@ function patch(instance, data, oldData) { if (!data) { return; } - // 序列化 - pauseTracking(); - data = JSON.parse(JSON.stringify(data)); - resetTracking(); + // 通常不用序列化,但是好像部分边界情况需要,目前还未排查到 + // pauseTracking() + // data = JSON.parse(JSON.stringify(data)) + // resetTracking() const ctx = instance.ctx; const mpType = ctx.mpType; if (mpType === 'page' || mpType === 'component') { @@ -4495,7 +4498,9 @@ function patch(instance, data, oldData) { const mpInstance = ctx.$scope; const keys = Object.keys(data); // data.__webviewId__ = mpInstance.data.__webviewId__ + pauseTracking(); const diffData = diff(data, oldData || getMPInstanceData(mpInstance, keys)); + resetTracking(); if (Object.keys(diffData).length) { console.log('[' + +new Date() + @@ -4891,46 +4896,6 @@ var plugin = { }, }; -/** - * Actual implementation - */ -function vFor(source, renderItem) { - let ret; - if (isArray(source) || isString(source)) { - ret = new Array(source.length); - for (let i = 0, l = source.length; i < l; i++) { - ret[i] = renderItem(source[i], i, i); - } - } - else if (typeof source === 'number') { - if ((process.env.NODE_ENV !== 'production') && !Number.isInteger(source)) { - warn$1(`The v-for range expect an integer value but got ${source}.`); - return []; - } - ret = new Array(source); - for (let i = 0; i < source; i++) { - ret[i] = renderItem(i + 1, i, i); - } - } - else if (isObject(source)) { - if (source[Symbol.iterator]) { - ret = Array.from(source, (item, i) => renderItem(item, i, i)); - } - else { - const keys = Object.keys(source); - ret = new Array(keys.length); - for (let i = 0, l = keys.length; i < l; i++) { - const key = keys[i]; - ret[i] = renderItem(source[key], key, i); - } - } - } - else { - ret = []; - } - return ret; -} - function vOn(value) { const instance = getCurrentInstance(); const name = 'e' + instance.$ei++; @@ -5000,6 +4965,46 @@ function patchStopImmediatePropagation(e, value) { } } +/** + * Actual implementation + */ +function vFor(source, renderItem) { + let ret; + if (isArray(source) || isString(source)) { + ret = new Array(source.length); + for (let i = 0, l = source.length; i < l; i++) { + ret[i] = renderItem(source[i], i, i); + } + } + else if (typeof source === 'number') { + if ((process.env.NODE_ENV !== 'production') && !Number.isInteger(source)) { + warn$1(`The v-for range expect an integer value but got ${source}.`); + return []; + } + ret = new Array(source); + for (let i = 0; i < source; i++) { + ret[i] = renderItem(i + 1, i, i); + } + } + else if (isObject(source)) { + if (source[Symbol.iterator]) { + ret = Array.from(source, (item, i) => renderItem(item, i, i)); + } + else { + const keys = Object.keys(source); + ret = new Array(keys.length); + for (let i = 0, l = keys.length; i < l; i++) { + const key = keys[i]; + ret[i] = renderItem(source[key], key, i); + } + } + } + else { + ret = []; + } + return ret; +} + function renderSlot(name, props = {}) { const instance = getCurrentInstance(); const vueIds = instance.attrs.vI; @@ -5069,10 +5074,21 @@ function setupDevtoolsPlugin() { // noop } +const o = (value) => vOn(value); +const f = (source, renderItem) => vFor(source, renderItem); +const r = (name, props) => renderSlot(name, props); +const w = (fn, options) => withScopedSlot(fn, options); +const s = (value) => stringifyStyle(value); +const c = (str) => camelize(str); +const e = (target, ...sources) => extend(target, ...sources); +const h = (str) => hyphenate(str); +const n = (value) => normalizeClass(value); +const t = (val) => toDisplayString(val); + function createApp(rootComponent, rootProps = null) { rootComponent && (rootComponent.mpType = 'app'); return createVueApp(rootComponent, rootProps).use(plugin); } const createSSRApp = createApp; -export { EffectScope, ReactiveEffect, callWithAsyncErrorHandling, callWithErrorHandling, computed, createApp, createSSRApp, createVNode$1 as createVNode, createVueApp, customRef, defineComponent, defineEmits, defineExpose, defineProps, effect, effectScope, vFor as f, getCurrentInstance, getCurrentScope, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, mergeDefaults, mergeProps, nextTick, vOn as o, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onUnmounted, onUpdated, patch, provide, proxyRefs, queuePostFlushCb, renderSlot as r, reactive, readonly, ref, resolveComponent, resolveDirective, resolveFilter, stringifyStyle as s, setupDevtoolsPlugin, shallowReactive, shallowReadonly, shallowRef, stop, toHandlers, toRaw, toRef, toRefs, triggerRef, unref, useAttrs, useSSRContext, useSlots, version, withScopedSlot as w, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withModifiers, withScopeId }; +export { EffectScope, ReactiveEffect, c, callWithAsyncErrorHandling, callWithErrorHandling, computed, createApp, createSSRApp, createVNode$1 as createVNode, createVueApp, customRef, defineComponent, defineEmits, defineExpose, defineProps, e, effect, effectScope, f, getCurrentInstance, getCurrentScope, h, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, mergeDefaults, mergeProps, n, nextTick, o, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onUnmounted, onUpdated, patch, provide, proxyRefs, queuePostFlushCb, r, reactive, readonly, ref, resolveComponent, resolveDirective, resolveFilter, s, setupDevtoolsPlugin, shallowReactive, shallowReadonly, shallowRef, stop, t, toHandlers, toRaw, toRef, toRefs, triggerRef, unref, useAttrs, useSSRContext, useSlots, version, w, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withModifiers, withScopeId }; diff --git a/packages/uni-mp-vue/lib/vue.runtime.esm.js b/packages/uni-mp-vue/lib/vue.runtime.esm.js index ce88a8e5e..d02594679 100644 --- a/packages/uni-mp-vue/lib/vue.runtime.esm.js +++ b/packages/uni-mp-vue/lib/vue.runtime.esm.js @@ -4290,6 +4290,9 @@ const version = "3.2.20"; */ const resolveFilter = null; +function unwrapper(target) { + return toRaw(unref(target)); +} // import deepCopy from './deepCopy' /** * https://raw.githubusercontent.com/Tencent/westore/master/packages/westore/utils/diff.js @@ -4304,7 +4307,7 @@ function diff(current, pre) { return result; } function syncKeys(current, pre) { - current = unref(current); + current = unwrapper(current); if (current === pre) return; const rootCurrentType = toTypeString(current); @@ -4329,7 +4332,7 @@ function syncKeys(current, pre) { } } function _diff(current, pre, path, result) { - current = unref(current); + current = unwrapper(current); if (current === pre) return; const rootCurrentType = toTypeString(current); @@ -4341,7 +4344,7 @@ function _diff(current, pre, path, result) { } else { for (let key in current) { - const currentValue = unref(current[key]); + const currentValue = unwrapper(current[key]); const preValue = pre[key]; const currentType = toTypeString(currentValue); const preType = toTypeString(preValue); @@ -4483,10 +4486,10 @@ function patch(instance, data, oldData) { if (!data) { return; } - // 序列化 - pauseTracking(); - data = JSON.parse(JSON.stringify(data)); - resetTracking(); + // 通常不用序列化,但是好像部分边界情况需要,目前还未排查到 + // pauseTracking() + // data = JSON.parse(JSON.stringify(data)) + // resetTracking() const ctx = instance.ctx; const mpType = ctx.mpType; if (mpType === 'page' || mpType === 'component') { @@ -4495,7 +4498,9 @@ function patch(instance, data, oldData) { const mpInstance = ctx.$scope; const keys = Object.keys(data); // data.__webviewId__ = mpInstance.data.__webviewId__ + pauseTracking(); const diffData = diff(data, oldData || getMPInstanceData(mpInstance, keys)); + resetTracking(); if (Object.keys(diffData).length) { console.log('[' + +new Date() + diff --git a/packages/uni-mp-vue/src/helpers/index.ts b/packages/uni-mp-vue/src/helpers/index.ts index cba5eadf7..3ff823585 100644 --- a/packages/uni-mp-vue/src/helpers/index.ts +++ b/packages/uni-mp-vue/src/helpers/index.ts @@ -1,6 +1,31 @@ -export { vFor } from './vFor' -export { vOn } from './vOn' -export { renderSlot } from './renderSlot' -export { withScopedSlot } from './withScopedSlot' -export { stringifyStyle } from './style' +import { + camelize, + extend, + hyphenate, + normalizeClass, + toDisplayString, +} from '@vue/shared' +import { vOn } from './vOn' +import { vFor, VForItem } from './vFor' +import { renderSlot } from './renderSlot' +import { withScopedSlot } from './withScopedSlot' +import { stringifyStyle } from './style' + export { setupDevtoolsPlugin } from './devtools' + +export const o: typeof vOn = (value) => vOn(value) +export const f: typeof vFor = ( + source: any, + renderItem: (...args: any[]) => VForItem +) => vFor(source, renderItem) +export const r: typeof renderSlot = (name, props) => renderSlot(name, props) +export const w: typeof withScopedSlot = (fn, options) => + withScopedSlot(fn, options) +export const s: typeof stringifyStyle = (value) => stringifyStyle(value) + +export const c: typeof camelize = (str) => camelize(str) +export const e: typeof extend = (target: object, ...sources: any[]) => + extend(target, ...sources) +export const h: typeof hyphenate = (str) => hyphenate(str) +export const n: typeof normalizeClass = (value) => normalizeClass(value) +export const t: typeof toDisplayString = (val) => toDisplayString(val) diff --git a/packages/uni-mp-vue/src/helpers/vFor.ts b/packages/uni-mp-vue/src/helpers/vFor.ts index ea06b7f75..433724108 100644 --- a/packages/uni-mp-vue/src/helpers/vFor.ts +++ b/packages/uni-mp-vue/src/helpers/vFor.ts @@ -1,7 +1,7 @@ import { isArray, isObject, isString } from '@vue/shared' import { warn } from 'vue' -type VForItem = Record +export type VForItem = Record /** * v-for string diff --git a/packages/uni-mp-vue/src/index.ts b/packages/uni-mp-vue/src/index.ts index f4b0e8283..44b818ecb 100644 --- a/packages/uni-mp-vue/src/index.ts +++ b/packages/uni-mp-vue/src/index.ts @@ -6,20 +6,6 @@ export function createApp(rootComponent: unknown, rootProps = null) { return createVueApp(rootComponent, rootProps).use(plugin) } export const createSSRApp = createApp -export { - vOn as o, - vFor as f, - renderSlot as r, - withScopedSlot as w, - stringifyStyle as s, - setupDevtoolsPlugin, -} from './helpers' -export { - camelize as c, - extend as e, - hyphenate as h, - normalizeClass as n, - toDisplayString as t, -} from '@vue/shared' +export * from './helpers' // @ts-ignore export * from 'vue' diff --git a/packages/vite-plugin-uni/src/cli/action.ts b/packages/vite-plugin-uni/src/cli/action.ts index 6d3aae7dd..f45d60302 100644 --- a/packages/vite-plugin-uni/src/cli/action.ts +++ b/packages/vite-plugin-uni/src/cli/action.ts @@ -6,15 +6,20 @@ import { CliOptions } from '.' import { build, buildSSR } from './build' import { createServer, createSSRServer } from './server' import { initEnv } from './utils' +import { initEasycom } from '../utils/easycom' export async function runDev(options: CliOptions & ServerOptions) { extend(options, { watch: true, minify: false }) initEnv('dev', options) try { if (options.platform === 'h5') { - await (options.ssr ? createSSRServer(options) : createServer(options)) + const server = await (options.ssr + ? createSSRServer(options) + : createServer(options)) + initEasycom(server.watcher) } else { const watcher = (await build(options)) as RollupWatcher + initEasycom() let isFirstStart = true let isFirstEnd = true watcher.on('event', (event) => { diff --git a/packages/vite-plugin-uni/src/cli/server.ts b/packages/vite-plugin-uni/src/cli/server.ts index 9f23f298c..48d2ed8ca 100644 --- a/packages/vite-plugin-uni/src/cli/server.ts +++ b/packages/vite-plugin-uni/src/cli/server.ts @@ -5,6 +5,7 @@ import { createLogger, createServer as createViteServer, ServerOptions, + ViteDevServer, } from 'vite' import express from 'express' import { printHttpServerUrls } from 'vite' @@ -34,9 +35,12 @@ export async function createServer(options: CliOptions & ServerOptions) { ) server.printUrls() + return server } -export async function createSSRServer(options: CliOptions & ServerOptions) { +export async function createSSRServer( + options: CliOptions & ServerOptions +): Promise { const app = express() /** * @type {import('vite').ViteDevServer} @@ -112,7 +116,7 @@ export async function createSSRServer(options: CliOptions & ServerOptions) { return new Promise((resolve, reject) => { const onSuccess = () => { printHttpServerUrls(server, vite.config) - resolve(server) + resolve(vite) } const onError = (e: Error & { code?: string }) => { if (e.code === 'EADDRINUSE') { diff --git a/packages/vite-plugin-uni/src/cli/utils.ts b/packages/vite-plugin-uni/src/cli/utils.ts index 7426be25a..bb4bf5362 100644 --- a/packages/vite-plugin-uni/src/cli/utils.ts +++ b/packages/vite-plugin-uni/src/cli/utils.ts @@ -55,6 +55,9 @@ export function initEnv(type: 'dev' | 'build', options: CliOptions) { ? path.resolve(process.env.UNI_HBUILDERX_PLUGINS!, 'uniapp-cli-vite') : process.cwd() + if (options.platform === 'app-plus') { + options.platform = 'app' + } process.env.UNI_PLATFORM = options.platform as UniApp.PLATFORM process.env.VITE_ROOT_DIR = process.env.UNI_INPUT_DIR || process.cwd() diff --git a/packages/vite-plugin-uni/src/config/build.ts b/packages/vite-plugin-uni/src/config/build.ts index 21a189ef6..cb394d4d8 100644 --- a/packages/vite-plugin-uni/src/config/build.ts +++ b/packages/vite-plugin-uni/src/config/build.ts @@ -6,7 +6,7 @@ import { VitePluginUniResolvedOptions } from '..' export function createBuild( options: VitePluginUniResolvedOptions ): UserConfig['build'] { - initEasycomsOnce(options.inputDir, options.platform) + const {} = initEasycomsOnce(options.inputDir, options.platform) return { chunkSizeWarningLimit: 100000000, rollupOptions: { diff --git a/packages/vite-plugin-uni/src/configureServer/easycom.ts b/packages/vite-plugin-uni/src/configureServer/easycom.ts deleted file mode 100644 index 8a9766782..000000000 --- a/packages/vite-plugin-uni/src/configureServer/easycom.ts +++ /dev/null @@ -1,26 +0,0 @@ -import debug from 'debug' -import { ViteDevServer } from 'vite' -import { debounce } from '@dcloudio/uni-shared' -import { initEasycomsOnce } from '@dcloudio/uni-cli-shared' -import { VitePluginUniResolvedOptions } from '..' - -const debugEasycom = debug('vite:uni:easycom') -export const serveEasycom = ( - server: ViteDevServer, - options: VitePluginUniResolvedOptions -) => { - const { filter, refresh } = initEasycomsOnce( - options.inputDir, - options.platform - ) - const refreshEasycom = debounce(refresh, 100) - server.watcher.on('all', (eventName, path) => { - if (!['add', 'unlink'].includes(eventName)) { - return - } - if (filter(path)) { - debugEasycom('watch', eventName, path) - refreshEasycom() - } - }) -} diff --git a/packages/vite-plugin-uni/src/configureServer/index.ts b/packages/vite-plugin-uni/src/configureServer/index.ts deleted file mode 100644 index 31c6cb7de..000000000 --- a/packages/vite-plugin-uni/src/configureServer/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Plugin } from 'vite' -import { VitePluginUniResolvedOptions } from '..' -import { serveEasycom } from './easycom' -import { serveStatic } from './static' - -export function createConfigureServer( - options: VitePluginUniResolvedOptions -): Plugin['configureServer'] { - return function (server) { - options.devServer = server - serveEasycom(server, options) - return () => { - serveStatic(server, options) - } - } -} diff --git a/packages/vite-plugin-uni/src/index.ts b/packages/vite-plugin-uni/src/index.ts index 7142a3932..64cfa738c 100644 --- a/packages/vite-plugin-uni/src/index.ts +++ b/packages/vite-plugin-uni/src/index.ts @@ -14,7 +14,6 @@ import { import { createConfig } from './config' import { createConfigResolved } from './configResolved' -import { createConfigureServer } from './configureServer' import { uniCopyPlugin } from './plugins/copy' import { initExtraPlugins, initPluginUniOptions } from './utils' import { @@ -109,7 +108,6 @@ export default function uniPlugin( config: createConfig(options, uniPlugins), // resolveId: createResolveId(options), configResolved: createConfigResolved(options), - configureServer: createConfigureServer(options), }) plugins.push(...uniPlugins) diff --git a/packages/vite-plugin-uni/src/utils/easycom.ts b/packages/vite-plugin-uni/src/utils/easycom.ts new file mode 100644 index 000000000..8aa8f5c1b --- /dev/null +++ b/packages/vite-plugin-uni/src/utils/easycom.ts @@ -0,0 +1,32 @@ +import debug from 'debug' +import type { FSWatcher } from 'chokidar' +import { debounce } from '@dcloudio/uni-shared' +import { chokidar, initEasycomsOnce } from '@dcloudio/uni-cli-shared' + +const debugEasycom = debug('vite:uni:easycom') +export const initEasycom = (watcher?: FSWatcher) => { + const { filter, refresh, options } = initEasycomsOnce( + process.env.UNI_INPUT_DIR, + process.env.UNI_PLATFORM + ) + if (!watcher) { + // build 模式,手动初始化 watcher + debugEasycom('initWatch', options.dirs!) + watcher = chokidar.watch(options.dirs!, { + ignored: ['**/node_modules/**', '**/.git/**'], + ignoreInitial: true, + ignorePermissionErrors: true, + disableGlobbing: true, + }) + } + const refreshEasycom = debounce(refresh, 100) + watcher.on('all', (eventName, path) => { + if (!['add', 'unlink'].includes(eventName)) { + return + } + if (filter(path)) { + debugEasycom('watch', eventName, path) + refreshEasycom() + } + }) +} -- GitLab