Skip to content

Commit

Permalink
refactor: enforce a cache directory (#6415)
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBarre committed Jan 16, 2022
1 parent 962d285 commit fb7ba53
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 50 deletions.
2 changes: 1 addition & 1 deletion docs/config/index.md
Expand Up @@ -169,7 +169,7 @@ export default defineConfig(async ({ command, mode }) => {
- **Type:** `string`
- **Default:** `"node_modules/.vite"`

Directory to save cache files. Files in this directory are pre-bundled deps or some other cache files generated by vite, which can improve the performance. You can use `--force` flag or manually delete the directory to regenerate the cache files. The value can be either an absolute file system path or a path relative to project root.
Directory to save cache files. Files in this directory are pre-bundled deps or some other cache files generated by vite, which can improve the performance. You can use `--force` flag or manually delete the directory to regenerate the cache files. The value can be either an absolute file system path or a path relative to project root. Default to `.vite` when no package.json is detected.

### resolve.alias

Expand Down
16 changes: 7 additions & 9 deletions packages/vite/src/node/build.ts
Expand Up @@ -431,15 +431,13 @@ async function doBuild(
if (ssr) {
// see if we have cached deps data available
let knownImports: string[] | undefined
if (config.cacheDir) {
const dataPath = path.join(config.cacheDir, '_metadata.json')
try {
const data = JSON.parse(
fs.readFileSync(dataPath, 'utf-8')
) as DepOptimizationMetadata
knownImports = Object.keys(data.optimized)
} catch (e) {}
}
const dataPath = path.join(config.cacheDir, '_metadata.json')
try {
const data = JSON.parse(
fs.readFileSync(dataPath, 'utf-8')
) as DepOptimizationMetadata
knownImports = Object.keys(data.optimized)
} catch (e) {}
if (!knownImports) {
// no dev deps optimization data, do a fresh scan
knownImports = Object.keys((await scanImports(config)).deps)
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/src/node/config.ts
Expand Up @@ -92,6 +92,7 @@ export interface UserConfig {
* the performance. You can use `--force` flag or manually delete the directory
* to regenerate the cache files. The value can be either an absolute file
* system path or a path relative to <root>.
* Default to `.vite` when no package.json is detected.
* @default 'node_modules/.vite'
*/
cacheDir?: string
Expand Down Expand Up @@ -244,6 +245,7 @@ export type ResolvedConfig = Readonly<
root: string
base: string
publicDir: string
cacheDir: string
command: 'build' | 'serve'
mode: string
isProduction: boolean
Expand Down Expand Up @@ -410,7 +412,9 @@ export async function resolveConfig(
)
const cacheDir = config.cacheDir
? path.resolve(resolvedRoot, config.cacheDir)
: pkgPath && path.join(path.dirname(pkgPath), `node_modules/.vite`)
: pkgPath
? path.join(path.dirname(pkgPath), `node_modules/.vite`)
: path.join(resolvedRoot, `.vite`)

const assetsFilter = config.assetsInclude
? createFilter(config.assetsInclude)
Expand Down
13 changes: 3 additions & 10 deletions packages/vite/src/node/http.ts
Expand Up @@ -122,7 +122,7 @@ export async function resolveHttpServer(

export async function resolveHttpsConfig(
https: boolean | HttpsServerOptions | undefined,
cacheDir: string | undefined
cacheDir: string
): Promise<HttpsServerOptions | undefined> {
if (!https) return undefined

Expand Down Expand Up @@ -152,14 +152,7 @@ function readFileIfExists(value?: string | Buffer | any[]) {
return value
}

async function createCertificateLazily() {
const { createCertificate } = await import('./certificate')
return createCertificate()
}

async function getCertificate(cacheDir?: string) {
if (!cacheDir) return await createCertificateLazily()

async function getCertificate(cacheDir: string) {
const cachePath = path.join(cacheDir, '_cert.pem')

try {
Expand All @@ -174,7 +167,7 @@ async function getCertificate(cacheDir?: string) {

return content
} catch {
const content = await createCertificateLazily()
const content = (await import('./certificate')).createCertificate()
fsp
.mkdir(cacheDir, { recursive: true })
.then(() => fsp.writeFile(cachePath, content))
Expand Down
5 changes: 0 additions & 5 deletions packages/vite/src/node/optimizer/index.ts
Expand Up @@ -118,11 +118,6 @@ export async function optimizeDeps(
const { root, logger, cacheDir } = config
const log = asCommand ? logger.info : debug

if (!cacheDir) {
log(`No cache directory. Skipping.`)
return null
}

const dataPath = path.join(cacheDir, '_metadata.json')
const mainHash = getDepHash(root, config)
const data: DepOptimizationMetadata = {
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -607,10 +607,9 @@ export function tryOptimizedResolve(
server: ViteDevServer,
importer?: string
): string | undefined {
const cacheDir = server.config.cacheDir
const depData = server._optimizeDepsMetadata

if (!cacheDir || !depData) return
if (!depData) return

const getOptimizedUrl = (optimizedData: typeof depData.optimized[string]) => {
return (
Expand Down
20 changes: 9 additions & 11 deletions packages/vite/src/node/server/index.ts
Expand Up @@ -561,18 +561,16 @@ export async function createServer(
middlewares.use(errorMiddleware(server, !!middlewareMode))

const runOptimize = async () => {
if (config.cacheDir) {
server._isRunningOptimizer = true
try {
server._optimizeDepsMetadata = await optimizeDeps(
config,
config.server.force || server._forceOptimizeOnRestart
)
} finally {
server._isRunningOptimizer = false
}
server._registerMissingImport = createMissingImporterRegisterFn(server)
server._isRunningOptimizer = true
try {
server._optimizeDepsMetadata = await optimizeDeps(
config,
config.server.force || server._forceOptimizeOnRestart
)
} finally {
server._isRunningOptimizer = false
}
server._registerMissingImport = createMissingImporterRegisterFn(server)
}

if (!middlewareMode && httpServer) {
Expand Down
17 changes: 6 additions & 11 deletions packages/vite/src/node/server/middlewares/transform.ts
Expand Up @@ -48,19 +48,14 @@ export function transformMiddleware(
} = server

// determine the url prefix of files inside cache directory
let cacheDirPrefix: string | undefined
if (cacheDir) {
const cacheDirRelative = normalizePath(path.relative(root, cacheDir))
if (cacheDirRelative.startsWith('../')) {
// if the cache directory is outside root, the url prefix would be something
const cacheDirRelative = normalizePath(path.relative(root, cacheDir))
const cacheDirPrefix = cacheDirRelative.startsWith('../')
? // if the cache directory is outside root, the url prefix would be something
// like '/@fs/absolute/path/to/node_modules/.vite'
cacheDirPrefix = `/@fs/${normalizePath(cacheDir).replace(/^\//, '')}`
} else {
// if the cache directory is inside root, the url prefix would be something
`/@fs/${normalizePath(cacheDir).replace(/^\//, '')}`
: // if the cache directory is inside root, the url prefix would be something
// like '/node_modules/.vite'
cacheDirPrefix = `/${cacheDirRelative}`
}
}
`/${cacheDirRelative}`

// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return async function viteTransformMiddleware(req, res, next) {
Expand Down

0 comments on commit fb7ba53

Please sign in to comment.