Skip to content

Commit

Permalink
fix: hmr error when server restart
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Sep 15, 2023
1 parent dfde99e commit 187f0d4
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 57 deletions.
2 changes: 1 addition & 1 deletion playground/spa/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*"
}
}
4 changes: 2 additions & 2 deletions playground/spa/public-typescript/manifest.json
Original file line number Diff line number Diff line change
@@ -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"
}
2 changes: 1 addition & 1 deletion playground/spa/public-typescript/test.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
console.log('test1')
console.log('test')
41 changes: 3 additions & 38 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/helper/AbsCacheProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export type BuildEndArgs = {
export interface IDeleteFile {
tsFileName: string
jsFileName?: string
/**
* if true, will not write file to disk
*/
silent?: boolean
}

Expand Down
14 changes: 11 additions & 3 deletions src/helper/utils.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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 = '') {
Expand All @@ -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)
}
}
}
30 changes: 18 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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,
Expand All @@ -167,19 +174,15 @@ 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)
}
}

async function handleFileAdded(filePath: string) {
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)
}
}

Expand Down Expand Up @@ -207,6 +210,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) {
return
}

// skip server restart when options not changed
if (eq(previousOpts, opts)) {
return
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 []
}
},
Expand All @@ -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,
})
Expand Down

0 comments on commit 187f0d4

Please sign in to comment.