diff --git a/lib/map-generator.js b/lib/map-generator.js index 49d638aac..58290aa60 100644 --- a/lib/map-generator.js +++ b/lib/map-generator.js @@ -16,6 +16,7 @@ class MapGenerator { this.root = root this.opts = opts this.css = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute } isMap() { @@ -97,10 +98,10 @@ class MapGenerator { let from = node.source.input.from if (from && !already[from]) { already[from] = true - this.map.setSourceContent( - this.toUrl(this.path(from)), - node.source.input.css - ) + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) } } }) @@ -232,17 +233,21 @@ class MapGenerator { return encodeURI(path).replace(/[#?]/g, encodeURIComponent) } + toFileUrl(path) { + if (pathToFileURL) { + return pathToFileURL(path).toString() + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + sourcePath(node) { if (this.mapOpts.from) { return this.toUrl(this.mapOpts.from) - } else if (this.mapOpts.absolute) { - if (pathToFileURL) { - return pathToFileURL(node.source.input.from).toString() - } else { - throw new Error( - '`map.absolute` option is not available in this PostCSS build' - ) - } + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) } else { return this.toUrl(this.path(node.source.input.from)) } diff --git a/test/map.test.ts b/test/map.test.ts index 7fc7ce529..91a459031 100755 --- a/test/map.test.ts +++ b/test/map.test.ts @@ -2,6 +2,7 @@ import { SourceMapConsumer, SourceMapGenerator } from 'source-map-js' import { removeSync, outputFileSync } from 'fs-extra' import { is, type, equal, match } from 'uvu/assert' import { join, resolve, parse } from 'path' +import { pathToFileURL } from 'url' import { existsSync } from 'fs' import { test } from 'uvu' @@ -722,4 +723,18 @@ test('supports previous inline map with empty processor', () => { match((root3.source?.input.origin(1, 0) as any).file, 'a.css') }) +test('absolute sourcemaps have source contents', () => { + let result = postcss([() => {}]).process('a{}', { + from: '/dir/to/a.css', + map: { + inline: false, + absolute: true + } + }) + equal(result.map.toJSON().sources, [ + pathToFileURL('/dir/to/a.css').toString() + ]) + equal(result.map.toJSON().sourcesContent, ['a{}']) +}) + test.run()