Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(css): simplify cached import code #12730

Merged
merged 1 commit into from
Apr 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 12 additions & 23 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1054,32 +1054,21 @@ async function compileCSS(
}
}

const lazyImportCache = new Map()
function createCachedImport<T>(
name: string,
imp: () => Promise<T>,
): () => T | Promise<T> {
function createCachedImport<T>(imp: () => Promise<T>): () => T | Promise<T> {
let cached: T | Promise<T>
return () => {
const cached = lazyImportCache.get(name)
if (cached) return cached

const promise = imp().then((module) => {
lazyImportCache.set(name, module)
return module
})
lazyImportCache.set(name, promise)
return promise
if (!cached) {
cached = imp().then((module) => {
cached = module
return module
})
}
return cached
}
}
const importPostcssImport = createCachedImport(
'postcss-import',
() => import('postcss-import'),
)
const importPostcssModules = createCachedImport(
'postcss-modules',
() => import('postcss-modules'),
)
const importPostcss = createCachedImport('postcss', () => import('postcss'))
const importPostcssImport = createCachedImport(() => import('postcss-import'))
const importPostcssModules = createCachedImport(() => import('postcss-modules'))
const importPostcss = createCachedImport(() => import('postcss'))

export interface PreprocessCSSResult {
code: string
Expand Down