From 7a96ac2232e8994de2aab3a125ac8c0a12732549 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Wed, 8 Sep 2021 14:35:34 +0800 Subject: [PATCH] fix(h5): history mode --- packages/uni-cli-shared/src/json/manifest.ts | 7 ++++ packages/uni-h5-vite/src/plugin/index.ts | 35 ++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/packages/uni-cli-shared/src/json/manifest.ts b/packages/uni-cli-shared/src/json/manifest.ts index 35b249901..ed2f19ff7 100644 --- a/packages/uni-cli-shared/src/json/manifest.ts +++ b/packages/uni-cli-shared/src/json/manifest.ts @@ -52,3 +52,10 @@ export function getUniStatistics(inputDir: string, platform: UniApp.PLATFORM) { manifest[platform] && manifest[platform].uniStatistics ) } + +export function getRouterOptions(manifestJson: Record): { + mode?: 'history' | 'hash' + base?: string +} { + return extend({}, manifestJson.h5?.router) +} diff --git a/packages/uni-h5-vite/src/plugin/index.ts b/packages/uni-h5-vite/src/plugin/index.ts index a7ad15be3..9b195ea8b 100644 --- a/packages/uni-h5-vite/src/plugin/index.ts +++ b/packages/uni-h5-vite/src/plugin/index.ts @@ -1,9 +1,13 @@ import fs from 'fs' import path from 'path' +import { parse as parseUrl } from 'url' import { isInHBuilderX, resolveMainPathOnce, UniVitePlugin, + getRouterOptions, + parseManifestJsonOnce, + EXTNAME_VUE_RE, } from '@dcloudio/uni-cli-shared' import { createHandleHotUpdate } from './handleHotUpdate' import { createTransformIndexHtml } from './transformIndexHtml' @@ -96,6 +100,37 @@ export const UniH5Plugin: UniVitePlugin = { } 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() + }) + } }, handleHotUpdate: createHandleHotUpdate(), transformIndexHtml: createTransformIndexHtml(), -- GitLab