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(css): convert map returned by vite:css transform to SourceMap (fixes #4939) #4950

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 27 additions & 5 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ async function compileCSS(
server?: ViteDevServer
): Promise<{
code: string
map?: SourceMap
map?: SourceMap | string
ast?: Postcss.Result
modules?: Record<string, string>
deps?: Set<string>
Expand All @@ -599,7 +599,7 @@ async function compileCSS(
return { code }
}

let map: SourceMap | undefined
let map: any | undefined // can be SourceMapGenerator or SourceMap or ?
let modules: Record<string, string> | undefined
const deps = new Set<string>()

Expand Down Expand Up @@ -639,7 +639,7 @@ async function compileCSS(
}

code = preprocessResult.code
map = preprocessResult.map as SourceMap
map = preprocessResult.map
if (preprocessResult.deps) {
preprocessResult.deps.forEach((dep) => {
// sometimes sass registers the file itself as a dep
Expand Down Expand Up @@ -708,7 +708,7 @@ async function compileCSS(
if (!postcssPlugins.length) {
return {
code,
map
map: convertToSourceMap(map)
}
}

Expand Down Expand Up @@ -769,12 +769,34 @@ async function compileCSS(
return {
ast: postcssResult,
code: postcssResult.css,
map: postcssResult.map as any,
map: convertToSourceMap(postcssResult.map),
modules,
deps
}
}

// utility function to turn map returned by postcss into a value that matches transform hook signature
function convertToSourceMap(map: any): SourceMap | string | undefined {
if (!map) {
return undefined
}
if (
map.constructor.name === 'SourceMapGenerator' &&
map._mappings &&
map.toJSON
) {
return map.toJSON()
}
if (typeof map === 'string' || (map.mappings && map.sources && map.version)) {
return map
}
throw new Error(
`failed to convert map to SourceMap format, expected SourceMapGenerator, SourceMap or string, got: ${JSON.stringify(
map
)}`
)
}

interface PostCSSConfigResult {
options: Postcss.ProcessOptions
plugins: Postcss.Plugin[]
Expand Down