Skip to content

Commit

Permalink
fix: only watch pages and layouts dir for module reloading
Browse files Browse the repository at this point in the history
allows for glob patterns and sets a sensible default
closes #94
  • Loading branch information
JohnCampionJr committed Dec 5, 2023
1 parent 33e011c commit 526fbf6
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 37 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,13 @@ Any files named `__*__.vue` will be excluded, and you can specify any additional

### pagesDir

Set this to avoid HMR reloading for all added or deleted files anywhere in the projet.
Defines the pages dir to avoid HMR reloading for all added or deleted files anywhere in the projet.

Relative path to the pages directory.
Relative path to the pages directory. If you want it to watch for all files, like in v0.8.0 or earlier, set to null.

**Default:** `null`
Can also be an array of layout dirs or use `**` glob patterns

**Default:** `'src/pages'`

## How it works

Expand Down
1 change: 1 addition & 0 deletions examples/spa/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.test { }
3 changes: 2 additions & 1 deletion examples/spa/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ const config = defineConfig({
}),
Layouts({
defaultLayout: 'default',
layoutsDirs: ['src/layouts', 'src/**/layouts'],
layoutsDirs: 'src/**/layouts',
pagesDirs: [],
}),
Markdown(),
],
Expand Down
4 changes: 4 additions & 0 deletions examples/vitesse/src/components/TheFooter.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ async function toggleLocales() {
<div i-carbon-dicom-overlay />
</RouterLink>

<RouterLink icon-btn to="/test" class="text-xs">
Test Layout
</RouterLink>

<a icon-btn rel="noreferrer" href="https://github.com/antfu/vitesse" target="_blank" title="GitHub">
<div i-carbon-logo-github />
</a>
Expand Down
52 changes: 21 additions & 31 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { resolve } from 'path'
import fg from 'fast-glob'
import type { ModuleNode, Plugin, ResolvedConfig } from 'vite'
import { createVirtualModuleCode } from './clientSide'
import { getFilesFromPath } from './files'
import { getImportCode } from './importCode'
import getClientCode from './RouteLayout'
import { debug, normalizePath } from './utils'
import { debug, normalizePath, resolveDirs } from './utils'

import type {
clientSideOptions,
Expand All @@ -29,7 +28,7 @@ function resolveOptions(userOptions: UserOptions): ResolvedOptions {
{
defaultLayout: 'default',
layoutsDirs: 'src/layouts',
pagesDir: null,
pagesDirs: 'src/pages',
extensions: ['vue'],
exclude: [],
importMode: defaultImportMode,
Expand All @@ -40,14 +39,21 @@ function resolveOptions(userOptions: UserOptions): ResolvedOptions {

export default function Layout(userOptions: UserOptions = {}): Plugin {
let config: ResolvedConfig

const options: ResolvedOptions = resolveOptions(userOptions)

let layoutDirs: string[]
let pagesDirs: string[]

// const pagesDirs = resolveDirs(options.pagesDirs, config.root)

return {
name: 'vite-plugin-vue-layouts',
enforce: 'pre',
configResolved(_config) {
config = _config
layoutDirs = resolveDirs(options.layoutsDirs, config.root)
pagesDirs = resolveDirs(options.pagesDirs, config.root)
},
configureServer({ moduleGraph, watcher, ws }) {
watcher.add(options.layoutsDirs)
Expand All @@ -64,17 +70,18 @@ export default function Layout(userOptions: UserOptions = {}): Plugin {
}
}

const absolutePagesDir = options.pagesDir ? normalizePath(resolve(process.cwd(), options.pagesDir)) : null
// const absolutePagesDir = options.pagesDir ? normalizePath(resolve(process.cwd(), options.pagesDir)) : null

const updateVirtualModule = (path: string) => {
path = `${normalizePath(path)}`

// If absolutePagesDir is defined and path doesn't correspond to pagesDir
if (absolutePagesDir && !~path.indexOf(absolutePagesDir))
return

const module = moduleGraph.getModuleById(MODULE_ID_VIRTUAL)
reloadModule(module)
path = normalizePath(path)

if (pagesDirs.length === 0 ||
pagesDirs.some(dir => path.startsWith(dir)) ||
layoutDirs.some(dir => path.startsWith(dir))) {
debug('reload', path)
const module = moduleGraph.getModuleById(MODULE_ID_VIRTUAL)
reloadModule(module)
}
}

watcher.on('add', (path) => {
Expand All @@ -86,9 +93,7 @@ export default function Layout(userOptions: UserOptions = {}): Plugin {
})

watcher.on('change', async(path) => {
path = `/${normalizePath(path)}`
const module = await moduleGraph.getModuleByUrl(path)
reloadModule(module, path)
updateVirtualModule(path)
})
},
resolveId(id) {
Expand All @@ -98,24 +103,9 @@ export default function Layout(userOptions: UserOptions = {}): Plugin {
},
async load(id) {
if (id === MODULE_ID_VIRTUAL) {
const layoutDirs = Array.isArray(options.layoutsDirs)
? options.layoutsDirs
: [options.layoutsDirs]
const container: FileContainer[] = []
const layoutDirsResolved: string[] = []

for (const dir of layoutDirs) {
if (dir.includes('**')) {
const matches = await fg(dir, { onlyDirectories: true })
for (const match of matches)
layoutDirsResolved.push(normalizePath(resolve(config.root, match)))
}
else {
layoutDirsResolved.push(dir)
}
}

for (const dir of layoutDirsResolved) {
const layoutsDirPath = dir.substr(0, 1) === '/'
? normalizePath(dir)
: normalizePath(resolve(config.root, dir))
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ interface Options {
layoutsDirs: string | string[]
/**
* Relative path to the pages directory.
* @default null
* @default 'src/pages'
*/
pagesDir?: string
pagesDirs: string | string[] | null
/**
* Valid file extensions for page components.
* @default ['vue']
Expand Down
22 changes: 22 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Debug from 'debug'
import fg from 'fast-glob'
import { resolve } from 'path'

export function extensionsToGlob(extensions: string[]) {
return extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0] || ''
Expand All @@ -13,3 +15,23 @@ export const debug = Debug('vite-plugin-layouts')
export function pathToName(filepath: string) {
return filepath.replace(/[_.\-\\/]/g, '_').replace(/[[:\]()]/g, '$')
}

export function resolveDirs(dirs: string | string[] | null, root: string) {
if (dirs === null) return []
const dirsArray = Array.isArray(dirs) ? dirs : [dirs]
const dirsResolved: string[] = []

for (const dir of dirsArray) {
if (dir.includes('**')) {
const matches = fg.sync(dir, { onlyDirectories: true })
for (const match of matches)
dirsResolved.push(normalizePath(resolve(root, match)))
}
else {
dirsResolved.push(normalizePath(resolve(root, dir)))
}
}

return dirsResolved

}

0 comments on commit 526fbf6

Please sign in to comment.