Skip to content

Commit

Permalink
feat: add cache when route block change to update
Browse files Browse the repository at this point in the history
close #95, #88
  • Loading branch information
KeJunMao committed Jul 29, 2023
1 parent 327f9c9 commit eddef32
Show file tree
Hide file tree
Showing 5 changed files with 77 additions and 19 deletions.
38 changes: 29 additions & 9 deletions packages/core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ import {
isConfigFile,
isTargetFile,
mergePageMetaDataArray,
useCachedPages,
} from './utils'
import { resolveOptions } from './options'
import { checkPagesJsonFile, getPageFiles, writeFileSync } from './files'
import { getRouteBlock } from './customBlock'
import { getRouteBlock, getRouteSfcBlock } from './customBlock'
import { OUTPUT_NAME } from './constant'

let lsatPagesJson = ''

const { setCache, hasChanged } = useCachedPages()
export class PageContext {
private _server: ViteDevServer | undefined

Expand Down Expand Up @@ -106,8 +110,8 @@ export class PageContext {
return

debug.pages(`File added: ${path}`)
this.updatePagesJSON()
this.onUpdate()
if (await this.updatePagesJSON())
this.onUpdate()
})

watcher.on('change', async (path) => {
Expand All @@ -116,8 +120,8 @@ export class PageContext {
return

debug.pages(`File changed: ${path}`)
this.updatePagesJSON()
this.onUpdate()
if (await this.updatePagesJSON(path))
this.onUpdate()
})

watcher.on('unlink', async (path) => {
Expand All @@ -126,8 +130,8 @@ export class PageContext {
return

debug.pages(`File removed: ${path}`)
this.updatePagesJSON()
this.onUpdate()
if (await this.updatePagesJSON())
this.onUpdate()
})
}

Expand All @@ -144,7 +148,9 @@ export class PageContext {

async parsePage(page: PagePath): Promise<PageMetaDatum> {
const { relativePath, absolutePath } = page
const routeBlock = await getRouteBlock(absolutePath, this.options)
const routeSfcBlock = await getRouteSfcBlock(absolutePath)
const routeBlock = await getRouteBlock(absolutePath, routeSfcBlock, this.options)
setCache(absolutePath, routeSfcBlock)
const relativePathWithFileName = relativePath.replace(path.extname(relativePath), '')
const pageMetaDatum: PageMetaDatum = {
path: normalizePath(relativePathWithFileName),
Expand Down Expand Up @@ -233,7 +239,14 @@ export class PageContext {
debug.subPages(this.subPageMetaData)
}

async updatePagesJSON() {
async updatePagesJSON(filepath?: string) {
if (filepath) {
if (!await hasChanged(filepath)) {
debug.cache(`The route block on page ${filepath} did not send any changes, skipping`)
return false
}
}

checkPagesJsonFile(this.resolvedPagesJSONPath)
this.options.onBeforeLoadUserConfig(this)
await this.loadUserPagesConfig()
Expand All @@ -260,9 +273,16 @@ export class PageContext {
}

const pagesJson = JSON.stringify(data, null, this.options.minify ? undefined : 2)
if (lsatPagesJson === pagesJson) {
debug.pages('PagesJson Not have change')
return false
}

writeFileSync(this.resolvedPagesJSONPath, pagesJson)
lsatPagesJson = pagesJson

this.options.onAfterWriteFile(this)
return true
}

virtualModule() {
Expand Down
11 changes: 6 additions & 5 deletions packages/core/src/customBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,17 @@ export function parseCustomBlock(
}
}

export async function getRouteBlock(path: string, options: ResolvedOptions): Promise<CustomBlock | undefined> {
export async function getRouteSfcBlock(path: string): Promise<SFCBlock | undefined> {
const content = fs.readFileSync(path, 'utf8')

const parsedSFC = await parseSFC(content)
const blockStr = parsedSFC?.customBlocks.find(b => b.type === 'route')

return blockStr
}

export async function getRouteBlock(path: string, blockStr?: SFCBlock, options: ResolvedOptions): Promise<CustomBlock | undefined> {
if (!blockStr)
return

const result = parseCustomBlock(blockStr, path, options)

return result
return parseCustomBlock(blockStr, path, options)
}
32 changes: 31 additions & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import Debug from 'debug'
import type { ModuleNode, ViteDevServer } from 'vite'
import { type ModuleNode, type ViteDevServer, normalizePath } from 'vite'
import { groupBy } from 'lodash-unified'
import fg from 'fast-glob'
import type { SFCBlock } from '@vue/compiler-sfc'
import { FILE_EXTENSIONS, RESOLVED_MODULE_ID_VIRTUAL } from './constant'
import type { PageMetaDatum } from './types'
import { getRouteSfcBlock } from './customBlock'

export function invalidatePagesModule(server: ViteDevServer) {
const { moduleGraph } = server
Expand All @@ -23,6 +25,7 @@ export const debug = {
pages: Debug('vite-plugin-uni-pages:pages'),
subPages: Debug('vite-plugin-uni-pages:subPages'),
error: Debug('vite-plugin-uni-pages:error'),
cache: Debug('vite-plugin-uni-pages:cache'),
}

export function extsToGlob(extensions: string[]) {
Expand Down Expand Up @@ -65,3 +68,30 @@ export async function getPagesConfigSourcePaths() {
absolute: true,
})
}

export function useCachedPages() {
const pages = new Map<string, string>()

function parseData(block?: SFCBlock) {
return {
content: block?.loc.source.trim() ?? '',
attr: block?.attrs ?? '',
}
}

function setCache(filePath: string, routeBlock?: SFCBlock) {
pages.set(filePath, JSON.stringify(parseData(routeBlock)))
}

async function hasChanged(filePath: string, routeBlock?: SFCBlock) {
if (!routeBlock)
routeBlock = await getRouteSfcBlock(normalizePath(filePath))

return !pages.has(filePath) || JSON.stringify(parseData(routeBlock)) !== pages.get(filePath)
}

return {
setCache,
hasChanged,
}
}
4 changes: 2 additions & 2 deletions packages/playground/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { createSSRApp } from 'vue'
import { pages, subPackages } from 'virtual:uni-pages'
// import { pages, subPackages } from 'virtual:uni-pages'
import App from './App.vue'

// eslint-disable-next-line no-console
console.log(pages, subPackages)
// console.log(pages, subPackages)

export function createApp() {
const app = createSSRApp(App)
Expand Down
11 changes: 9 additions & 2 deletions packages/playground/src/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ function nav() {
url: '/pages/test',
})
}
throw new Error('233')
const count = ref(0)
</script>

<template>
Expand All @@ -22,6 +21,14 @@ throw new Error('233')
<button @click="nav">
nav
</button>

<button @click="count--">
-
</button>
{{ count }}
<button @click="count++">
+
</button>
</view>
</template>

Expand Down

0 comments on commit eddef32

Please sign in to comment.