Skip to content

Commit

Permalink
Feat: better cache handling
Browse files Browse the repository at this point in the history
- Adds option `cacheDir` - Choose the directory to use for caching
- Adds option `clearCache` - Clears the cache before processing
- Cache dir by default is under the package's `node_modules` folder
- Relative `cacheDir` path will be relative to Vite's `<root>` dir
- Absolute `cacheDir` path will be just that
  • Loading branch information
vHeemstra committed Nov 20, 2023
1 parent 0d5bfbe commit 4782821
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 7 deletions.
34 changes: 28 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import {
mkdirSync,
lstatSync,
readdirSync,
unlinkSync /*, rmSync */,
unlinkSync,
copyFileSync,
rmSync,
} from 'node:fs'
import { readFile, writeFile } from 'node:fs/promises'
import { Buffer } from 'node:buffer'
Expand All @@ -24,6 +25,8 @@ import {
isFilterPattern,
escapeRegExp,
smartEnsureDirs,
getPackageDirectory,
getPackageName,
} from './utils'

import type { PluginOption, ResolvedConfig } from 'vite'
Expand Down Expand Up @@ -151,6 +154,8 @@ export const parseOptions = (
? _options.skipIfLarger
: true,
cache: isBoolean(_options?.cache) ? _options.cache : true,
cacheDir: isString(_options?.cacheDir) ? _options.cacheDir : undefined,
clearCache: isBoolean(_options?.clearCache) ? _options.clearCache : false,
plugins,
makeAvif,
makeWebp,
Expand Down Expand Up @@ -808,11 +813,25 @@ export default function viteImagemin(_options: ConfigOptions): PluginOption {
: path.resolve(process.cwd(), rootDir),
)

// Note: Only cacheDir has a trailing slash.
if (isString(options.cacheDir)) {
cacheDir =
normalizePath(
path.isAbsolute(options.cacheDir)
? options.cacheDir
: path.resolve(rootDir, options.cacheDir),
) + '/'
} else {
const packageDir = normalizePath(getPackageDirectory())
cacheDir = `${packageDir}/node_modules/.cache/vite-plugin-imagemin/${getPackageName(
packageDir,
)}/`
}

// sourceDir = normalizePath(path.resolve(rootDir, entry))
outDir = normalizePath(path.resolve(rootDir, config.build.outDir))
assetsDir = normalizePath(path.resolve(outDir, config.build.assetsDir))
// publicDir = normalizePath(path.resolve(rootDir, config.publicDir))
cacheDir = `${rootDir}/node_modules/.cache/vite-plugin-imagemin/`

// const emptyOutDir = config.build.emptyOutDir || pathIsWithin(rootDir, outDir)

Expand All @@ -825,19 +844,22 @@ export default function viteImagemin(_options: ConfigOptions): PluginOption {

logger.info('')

// Create cache
// Init cache
if (options.clearCache) {
rmSync(cacheDir.slice(0, -1), { recursive: true, force: true })
}
if (options.cache !== false) {
mkdirSync(cacheDir.slice(0, -1), { recursive: true })

cache = (await createCache({
// noCache: options.cache === false,
cacheDirectory: cacheDir.slice(0, -1),
mode: 'content',
keys: [
() => {
return JSON.stringify(options)
},
],
})) as CacheInterface

mkdirSync(cacheDir.slice(0, -1), { recursive: true })
}

const processDir = onlyAssets ? assetsDir : outDir
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,21 @@ export interface ConfigOptions {
*/
cache?: boolean

/**
* Path of the directory to use for caching.
* Either:
* - relative path to Vite's root
* - absolute path
* @default <packageRoot>/node_modules/.cache/vite-plugin-imagemin
*/
cacheDir?: string

/**
* Force-clear the cache.
* @default false
*/
clearCache?: boolean

/**
* Only use optimized contents if smaller than original.
* @default true
Expand Down Expand Up @@ -136,6 +151,8 @@ export interface ResolvedConfigOptions {
verbose: boolean
skipIfLarger: boolean
cache: boolean
cacheDir?: string
clearCache: boolean
plugins: ResolvedPluginsConfig
makeAvif: false | ResolvedMakeConfigOptions
makeWebp: false | ResolvedMakeConfigOptions
Expand Down
39 changes: 38 additions & 1 deletion packages/core/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { existsSync, mkdirSync } from 'node:fs'
import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
import { dirname, join, parse, resolve } from 'node:path'
import { cwd } from 'node:process'
import { FilterPattern } from 'vite'
// import { ensureDirSync } from 'fs-extra'

Expand Down Expand Up @@ -66,3 +68,38 @@ export function smartEnsureDirs(filePaths: string[], mode = 0o0755): string[] {
return dir
})
}

export function getPackageDirectory() {
let filePath = ''
let directory = resolve(cwd())
const { root } = parse(directory)
const stopAt = resolve(directory, root)

while (directory && directory !== stopAt && directory !== root) {
filePath = join(directory, 'package.json')

try {
const stats = statSync(filePath, { throwIfNoEntry: false })
if (stats?.isFile()) {
break
}
} catch {
/* ignore */
}

directory = dirname(directory)
}

return filePath && dirname(filePath)
}

export const getPackageName = (pkgPath: string) => {
const pkgFile = join(pkgPath, 'package.json')
try {
const pkg = readFileSync(pkgFile, 'utf8')
const pkgJson = JSON.parse(pkg)
return pkgJson.name
} catch {
return 'file-cache'
}
}
2 changes: 2 additions & 0 deletions packages/playground/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export default defineConfig({
// skipIfLargerThan: 'smallest',
},
// cache: false,
// clearCache: true,
// cacheDir: 'cache',
}),
],
})

0 comments on commit 4782821

Please sign in to comment.