From 187f0d40d7737ab07bd85bafcb9c2dd97c509f3c Mon Sep 17 00:00:00 2001 From: hemengke1997 <23536175@qq.com> Date: Fri, 15 Sep 2023 23:24:10 +0800 Subject: [PATCH] fix: hmr error when server restart --- playground/spa/package.json | 2 +- .../spa/public-typescript/manifest.json | 4 +- playground/spa/public-typescript/test.ts | 2 +- pnpm-lock.yaml | 41 ++----------------- src/helper/AbsCacheProcessor.ts | 3 ++ src/helper/utils.ts | 14 +++++-- src/index.ts | 30 ++++++++------ 7 files changed, 39 insertions(+), 57 deletions(-) diff --git a/playground/spa/package.json b/playground/spa/package.json index 1193d94..ea477a7 100644 --- a/playground/spa/package.json +++ b/playground/spa/package.json @@ -20,7 +20,7 @@ "@vitejs/plugin-react": "^4.0.4", "cross-env": "^7.0.3", "typescript": "^4.9.5", - "vite": "4.4.9", + "vite": "^4.3.0", "vite-plugin-public-typescript": "workspace:*" } } diff --git a/playground/spa/public-typescript/manifest.json b/playground/spa/public-typescript/manifest.json index e41cac4..f760989 100644 --- a/playground/spa/public-typescript/manifest.json +++ b/playground/spa/public-typescript/manifest.json @@ -1,5 +1,5 @@ { + "test": "/out/test.e29e5748.js", "haha": "/out/haha.bdaaba63.js", - "index": "/out/index.a7db5a4b.js", - "test": "/out/test.61522cc4.js" + "index": "/out/index.a7db5a4b.js" } diff --git a/playground/spa/public-typescript/test.ts b/playground/spa/public-typescript/test.ts index aed99d4..4b2e663 100644 --- a/playground/spa/public-typescript/test.ts +++ b/playground/spa/public-typescript/test.ts @@ -1 +1 @@ -console.log('test1') +console.log('test') diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 72e245a..e666363 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -107,8 +107,8 @@ importers: specifier: ^4.9.5 version: 4.9.5 vite: - specifier: 4.4.9 - version: 4.4.9 + specifier: ^4.3.0 + version: 4.4.9(@types/node@20.6.0) vite-plugin-public-typescript: specifier: workspace:* version: link:../.. @@ -1485,7 +1485,7 @@ packages: '@babel/plugin-transform-react-jsx-self': 7.22.5(@babel/core@7.22.17) '@babel/plugin-transform-react-jsx-source': 7.22.5(@babel/core@7.22.17) react-refresh: 0.14.0 - vite: 4.4.9 + vite: 4.4.9(@types/node@20.6.0) transitivePeerDependencies: - supports-color dev: true @@ -5857,41 +5857,6 @@ packages: - terser dev: true - /vite@4.4.9: - resolution: {integrity: sha512-2mbUn2LlUmNASWwSCNSJ/EG2HuSRTnVNaydp6vMCm5VIqJsjMfbIWtbH2kDuwUVW5mMUKKZvGPX/rqeqVvv1XA==} - engines: {node: ^14.18.0 || >=16.0.0} - hasBin: true - peerDependencies: - '@types/node': '>= 14' - less: '*' - lightningcss: ^1.21.0 - sass: '*' - stylus: '*' - sugarss: '*' - terser: ^5.4.0 - peerDependenciesMeta: - '@types/node': - optional: true - less: - optional: true - lightningcss: - optional: true - sass: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - dependencies: - esbuild: 0.18.20 - postcss: 8.4.29 - rollup: 3.29.1 - optionalDependencies: - fsevents: 2.3.3 - dev: true - /vite@4.4.9(@types/node@18.17.15): resolution: {integrity: sha512-2mbUn2LlUmNASWwSCNSJ/EG2HuSRTnVNaydp6vMCm5VIqJsjMfbIWtbH2kDuwUVW5mMUKKZvGPX/rqeqVvv1XA==} engines: {node: ^14.18.0 || >=16.0.0} diff --git a/src/helper/AbsCacheProcessor.ts b/src/helper/AbsCacheProcessor.ts index af639c7..3c3e409 100644 --- a/src/helper/AbsCacheProcessor.ts +++ b/src/helper/AbsCacheProcessor.ts @@ -14,6 +14,9 @@ export type BuildEndArgs = { export interface IDeleteFile { tsFileName: string jsFileName?: string + /** + * if true, will not write file to disk + */ silent?: boolean } diff --git a/src/helper/utils.ts b/src/helper/utils.ts index a05e09c..118cac5 100644 --- a/src/helper/utils.ts +++ b/src/helper/utils.ts @@ -1,6 +1,6 @@ import path from 'path' import { createHash } from 'crypto' -import type { WebSocketServer } from 'vite' +import type { ResolvedConfig, WebSocketServer } from 'vite' import { normalizePath } from 'vite' import fs from 'fs-extra' import createDebug from 'debug' @@ -173,8 +173,7 @@ export function normalizeDirPath(dir: string) { } export function addCodeHeader(code: string) { - return `// gen via vite-plugin-public-typescript (only show in serve mode); - ${code}` + return `// gen via vite-plugin-public-typescript (show in serve mode only)\n${code}` } export function getInputDir(resolvedRoot: string, originInputDir: string, suffix = '') { @@ -195,3 +194,12 @@ export async function findAllOldJsFile(args: { publicDir: string; outputDir: str } return oldFiles } + +export function disableManifestHmr(config: ResolvedConfig, manifestPath: string) { + if (config.command === 'serve') { + const index = config.configFileDependencies.indexOf(manifestPath) + if (index !== -1) { + config.configFileDependencies.splice(index, 1) + } + } +} diff --git a/src/index.ts b/src/index.ts index 5d5446e..95778c7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,11 +11,13 @@ import { TS_EXT, _isPublicTypescript, addCodeHeader, + disableManifestHmr, eq, findAllOldJsFile, getInputDir, isEmptyObject, normalizeDirPath, + reloadPage, validateOptions, } from './helper/utils' import { build, buildAll, esbuildTypescript } from './helper/build' @@ -142,17 +144,22 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { cache.initCacheFromFile() + disableManifestHmr(c, cache.getManifestPath()) + debug('cache manifestPath:', cache.getManifestPath()) debug('cache:', cache.get()) assert(cache.getManifestPath().includes('.json')) }, - configureServer() { + + configureServer(server) { if (process.env.VITEST || process.env.CI) { return } + const { ws } = server + try { const watcher = new Watcher(globalConfigBuilder.get().absInputDir, { ignoreInitial: true, @@ -167,9 +174,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { const fileName = path.parse(filePath).name debug('unlink:', fileName) await globalConfigBuilder.get().cacheProcessor.deleteOldJs({ tsFileName: fileName }) - // TODO: fix hmr - // reloadPage(ws) - // server.restart() + reloadPage(ws) } } @@ -177,9 +182,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { if (_isPublicTypescript(filePath)) { debug('file added:', filePath) await build({ filePath }, (args) => globalConfigBuilder.get().cacheProcessor.onTsBuildEnd(args)) - // TODO: fix hmr - // reloadPage(ws) - // server.restart() + reloadPage(ws) } } @@ -207,6 +210,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { return } + // skip server restart when options not changed if (eq(previousOpts, opts)) { return } @@ -288,7 +292,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { cacheItem = c[fileName] } - if (cacheItem.path) { + if (cacheItem) { const attrs = node.attrs .reduce((acc, attr) => { if (attr.name === vppt.name) { @@ -318,13 +322,15 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { }, }, async handleHotUpdate(ctx) { - const { file } = ctx + const { file, server } = ctx if (_isPublicTypescript(file)) { debug('hmr:', file) + await build({ filePath: file }, (args) => globalConfigBuilder.get().cacheProcessor.onTsBuildEnd(args)) - // TODO: fix hmr - // ctx.server.restart() + + reloadPage(server.ws) + return [] } }, @@ -349,7 +355,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) { const cacheItem = cache.findCacheItemByPath(req.url) if (cacheItem) { return send(req, res, addCodeHeader(cacheItem._code || ''), 'js', { - cacheControl: 'no-cache', + cacheControl: 'max-age=31536000,immutable', headers: server.config.server.headers, map: null, })