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

fix: ensure new CSS modules cache at build start #3516

Merged
merged 3 commits into from
May 25, 2021
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
25 changes: 18 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ export const chunkToEmittedCssFileMap = new WeakMap<
*/
export function cssPlugin(config: ResolvedConfig): Plugin {
let server: ViteDevServer
const moduleCache = new Map<string, Record<string, string>>()
cssModulesCache.set(config, moduleCache)
let moduleCache: Map<string, Record<string, string>>

const resolveUrl = config.createResolver({
preferRelative: true,
Expand All @@ -135,6 +134,12 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
server = _server
},

buildStart() {
// Ensure a new cache for every build (i.e. rebuilding in watch mode)
moduleCache = new Map<string, Record<string, string>>()
cssModulesCache.set(config, moduleCache)
},

async transform(raw, id) {
if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) {
return
Expand Down Expand Up @@ -218,24 +223,30 @@ export function cssPlugin(config: ResolvedConfig): Plugin {
* Plugin applied after user plugins
*/
export function cssPostPlugin(config: ResolvedConfig): Plugin {
const styles = new Map<string, string>()
const pureCssChunks = new Set<string>()
const moduleCache = cssModulesCache.get(config)!
let styles: Map<string, string>
let pureCssChunks: Set<string>

// when there are multiple rollup outputs and extracting CSS, only emit once,
// since output formats have no effect on the generated CSS.
const outputToExtractedCSSMap = new Map<NormalizedOutputOptions, string>()
let outputToExtractedCSSMap: Map<NormalizedOutputOptions, string>
let hasEmitted = false

return {
name: 'vite:css-post',

buildStart() {
// Ensure new caches for every build (i.e. rebuilding in watch mode)
styles = new Map<string, string>()
pureCssChunks = new Set<string>()
outputToExtractedCSSMap = new Map<NormalizedOutputOptions, string>()
},

transform(css, id, ssr) {
if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) {
return
}

const modules = moduleCache.get(id)
const modules = cssModulesCache.get(config)!.get(id)
const modulesCode =
modules && dataToEsm(modules, { namedExports: true, preferConst: true })

Expand Down