From 732c3bc76a09269f58565c911d01cbdf20a698d4 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 27 Feb 2022 00:05:10 +0900 Subject: [PATCH 01/27] feat(dev): css sourcemap --- .../src/node/__tests__/plugins/css.spec.ts | 39 ++++++++++++++ packages/vite/src/node/plugins/css.ts | 53 +++++++++++++++---- packages/vite/src/node/server/send.ts | 12 +---- packages/vite/src/node/utils.ts | 8 +++ 4 files changed, 92 insertions(+), 20 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 539ec2f1af1810..9a61efaf02bbb1 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -2,6 +2,7 @@ import { cssUrlRE, cssPlugin } from '../../plugins/css' import { resolveConfig } from '../../config' import fs from 'fs' import path from 'path' +import { normalizePath } from '../../utils' describe('search css url function', () => { test('some spaces before it', () => { @@ -114,3 +115,41 @@ describe('css path resolutions', () => { mockFs.mockReset() }) }) + +describe('css source maps', () => { + const root = normalizePath(process.cwd()) + + test('cssmodule', async () => { + const config = await resolveConfig( + { + root + }, + 'serve' + ) + const { transform, buildStart } = cssPlugin(config) + + await buildStart.call({}) + + const { map } = await transform.call( + { + addWatchFile() { + return + } + }, + ` + .foo { + color: red; + } + `, + `${root}/foo.module.css` + ) + + expect(map).toStrictEqual({ + file: `${root}/foo.module.css`, + mappings: ';QACQ;UACE,UAAU;QACZ', + names: [], + sources: [`${root}/foo.module.css`], + version: 3 + }) + }) +}) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index cb62b785732e0d..5724b8cb09b76f 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -11,17 +11,19 @@ import { isObject, normalizePath, processSrcSet, - parseRequest + parseRequest, + genSourceMapUrl } from '../utils' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import postcssrc from 'postcss-load-config' import type { + ExistingRawSourceMap, NormalizedOutputOptions, OutputChunk, RenderedChunk, RollupError, - SourceMap + SourceMapInput } from 'rollup' import { dataToEsm } from '@rollup/pluginutils' import colors from 'picocolors' @@ -45,6 +47,8 @@ import type { Alias } from 'types/alias' import type { ModuleNode } from '../server/moduleGraph' import { transform, formatMessages } from 'esbuild' import { addToHTMLProxyTransformResult } from './html' +import type { RawSourceMap } from 'source-map-js' +import { injectSourcesContent } from '../server/sourcemap' // const debug = createDebugger('vite:css') @@ -184,7 +188,8 @@ export function cssPlugin(config: ResolvedConfig): Plugin { const { code: css, modules, - deps + deps, + map } = await compileCSS( id, raw, @@ -251,8 +256,7 @@ export function cssPlugin(config: ResolvedConfig): Plugin { return { code: css, - // TODO CSS source map - map: { mappings: '' } + map } } } @@ -302,12 +306,17 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (inlined) { return `export default ${JSON.stringify(css)}` } + const sourcemap = this.getCombinedSourcemap() + await injectSourcesContent(sourcemap, cleanUrl(id), config.logger) + const cssContent = `${css}\n/*# sourceMappingURL=${genSourceMapUrl( + sourcemap + )} */` return [ `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify( path.posix.join(config.base, CLIENT_PUBLIC_PATH) )}`, `const __vite__id = ${JSON.stringify(id)}`, - `const __vite__css = ${JSON.stringify(css)}`, + `const __vite__css = ${JSON.stringify(cssContent)}`, `__vite__updateStyle(__vite__id, __vite__css)`, // css modules exports change on edit so it can't self accept `${ @@ -604,7 +613,7 @@ async function compileCSS( server?: ViteDevServer ): Promise<{ code: string - map?: SourceMap + map?: SourceMapInput ast?: Postcss.Result modules?: Record deps?: Set @@ -629,7 +638,7 @@ async function compileCSS( return { code } } - let map: SourceMap | undefined + let map: ExistingRawSourceMap | string | undefined let modules: Record | undefined const deps = new Set() @@ -669,7 +678,8 @@ async function compileCSS( } code = preprocessResult.code - map = preprocessResult.map as SourceMap + // TODO: preprocessor source maps not supported currently + // map = preprocessResult.map if (preprocessResult.deps) { preprocessResult.deps.forEach((dep) => { // sometimes sass registers the file itself as a dep @@ -757,6 +767,7 @@ async function compileCSS( map: { inline: false, annotation: false, + sourcesContent: false, prev: map } }) @@ -804,12 +815,34 @@ async function compileCSS( return { ast: postcssResult, code: postcssResult.css, - map: postcssResult.map as any, + map: formatPostcssSourceMap(postcssResult.map.toJSON(), id), modules, deps } } +function formatPostcssSourceMap( + rawMap: RawSourceMap, + file: string +): ExistingRawSourceMap { + const inputFileDir = path.dirname(file) + const sources = rawMap.sources + // remove from sources, to prevent source map to be combined incorrectly + .filter((source) => source !== '') + .map((source) => { + const cleanSource = cleanUrl(decodeURIComponent(source)) + return normalizePath(path.resolve(inputFileDir, cleanSource)) + }) + + return { + file, + mappings: rawMap.mappings, + names: rawMap.names, + sources, + version: +rawMap.version + } +} + interface PostCSSConfigResult { options: Postcss.ProcessOptions plugins: Postcss.Plugin[] diff --git a/packages/vite/src/node/server/send.ts b/packages/vite/src/node/server/send.ts index 43f0fe1660b2eb..3523fbc7e971fe 100644 --- a/packages/vite/src/node/server/send.ts +++ b/packages/vite/src/node/server/send.ts @@ -1,6 +1,7 @@ import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'http' import getEtag from 'etag' import type { SourceMap } from 'rollup' +import { genSourceMapUrl } from '../utils' const isDebug = process.env.DEBUG @@ -59,18 +60,9 @@ export function send( '*\\/' )}*/\n` } - content += genSourceMapString(map) + content += `\n//# sourceMappingURL=${genSourceMapUrl(map)}` } res.statusCode = 200 return res.end(content) } - -function genSourceMapString(map: SourceMap | string | undefined) { - if (typeof map !== 'string') { - map = JSON.stringify(map) - } - return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from( - map - ).toString('base64')}` -} diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index bc1b8588cb212d..b3483f8cd5dc26 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -21,6 +21,7 @@ import type { } from '@ampproject/remapping/dist/types/types' import { performance } from 'perf_hooks' import { parse as parseUrl, URLSearchParams } from 'url' +import type { SourceMap } from 'rollup' export function slash(p: string): string { return p.replace(/\\/g, '/') @@ -642,3 +643,10 @@ export function parseRequest(id: string): Record | null { } return Object.fromEntries(new URLSearchParams(search.slice(1))) } + +export function genSourceMapUrl(map: SourceMap | string | undefined) { + if (typeof map !== 'string') { + map = JSON.stringify(map) + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}` +} From 38c0052fe708f93b1127a2467f20d37763a23b0a Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 27 Feb 2022 20:41:56 +0900 Subject: [PATCH 02/27] feat(dev): sass sourcemap --- .../src/node/__tests__/plugins/css.spec.ts | 124 +++++++++++++----- packages/vite/src/node/plugins/css.ts | 34 +++-- 2 files changed, 116 insertions(+), 42 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 9a61efaf02bbb1..735eeb6ad6733e 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -118,38 +118,96 @@ describe('css path resolutions', () => { describe('css source maps', () => { const root = normalizePath(process.cwd()) + const testcases = [ + { + name: 'cssmodule', + code: ` + .foo { + color: red; + } + `, + id: `${root}/foo.module.css`, + expectedMap: { + file: `${root}/foo.module.css`, + mappings: ';IACI;MACE,UAAU;IACZ', + names: [], + sources: [`${root}/foo.module.css`], + version: 3 + } + }, + { + name: 'sass', + code: ` + .foo + color: red + `, + id: `${root}/foo.sass`, + expectedMap: { + file: `${root}/foo.sass`, + mappings: 'AACI;EACE', + names: [], + sources: [`${root}/foo.sass`], + version: 3 + } + }, + { + name: 'scss', + code: ` + .foo { + color: red; + } + `, + id: `${root}/foo.scss`, + expectedMap: { + file: `${root}/foo.scss`, + mappings: 'AACM;EACE', + names: [], + sources: [`${root}/foo.scss`], + version: 3 + } + }, + { + name: 'scss module', + code: ` + .foo { + color: red; + } + `, + id: `${root}/foo.module.scss`, + expectedMap: { + file: `${root}/foo.module.scss`, + mappings: 'AACM;EACE', + names: [], + sources: [`${root}/foo.module.scss`], + version: 3 + } + } + ] + + test.concurrent.each(testcases)( + '$name', + async ({ code, id, expectedMap }) => { + const config = await resolveConfig( + { + root + }, + 'serve' + ) + const { transform, buildStart } = cssPlugin(config) + + await buildStart.call({}) + + const { map } = await transform.call( + { + addWatchFile() { + return + } + }, + code, + id + ) - test('cssmodule', async () => { - const config = await resolveConfig( - { - root - }, - 'serve' - ) - const { transform, buildStart } = cssPlugin(config) - - await buildStart.call({}) - - const { map } = await transform.call( - { - addWatchFile() { - return - } - }, - ` - .foo { - color: red; - } - `, - `${root}/foo.module.css` - ) - - expect(map).toStrictEqual({ - file: `${root}/foo.module.css`, - mappings: ';QACQ;UACE,UAAU;QACZ', - names: [], - sources: [`${root}/foo.module.css`], - version: 3 - }) - }) + expect(map).toMatchObject(expectedMap) + } + ) }) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 5724b8cb09b76f..bf6bb01d476894 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -12,7 +12,8 @@ import { normalizePath, processSrcSet, parseRequest, - genSourceMapUrl + genSourceMapUrl, + combineSourcemaps } from '../utils' import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' @@ -638,7 +639,7 @@ async function compileCSS( return { code } } - let map: ExistingRawSourceMap | string | undefined + let preprocessorMap: ExistingRawSourceMap | undefined let modules: Record | undefined const deps = new Set() @@ -678,8 +679,7 @@ async function compileCSS( } code = preprocessResult.code - // TODO: preprocessor source maps not supported currently - // map = preprocessResult.map + preprocessorMap = preprocessResult.map if (preprocessResult.deps) { preprocessResult.deps.forEach((dep) => { // sometimes sass registers the file itself as a dep @@ -753,7 +753,7 @@ async function compileCSS( if (!postcssPlugins.length) { return { code, - map + map: preprocessorMap } } @@ -768,7 +768,8 @@ async function compileCSS( inline: false, annotation: false, sourcesContent: false, - prev: map + // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources` + // prev: preprocessorMap, } }) @@ -812,10 +813,18 @@ async function compileCSS( } } + const postcssMap = formatPostcssSourceMap(postcssResult.map.toJSON(), id) + const combinedMap = preprocessorMap + ? combineSourcemaps(id, [ + { ...postcssMap, version: 3 }, + { ...preprocessorMap, version: 3 } + ]) + : postcssMap + return { ast: postcssResult, code: postcssResult.css, - map: formatPostcssSourceMap(postcssResult.map.toJSON(), id), + map: combinedMap as ExistingRawSourceMap, modules, deps } @@ -1041,7 +1050,7 @@ type SassStylePreprocessor = ( export interface StylePreprocessorResults { code: string - map?: object + map?: ExistingRawSourceMap | undefined errors: RollupError[] deps: string[] } @@ -1111,7 +1120,10 @@ const scss: SassStylePreprocessor = async ( data: await getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, - importer + importer, + sourceMap: true, + omitSourceMapUrl: true, + sourceMapRoot: path.dirname(options.filename) } try { @@ -1125,9 +1137,13 @@ const scss: SassStylePreprocessor = async ( }) }) const deps = result.stats.includedFiles + const map: ExistingRawSourceMap | undefined = result.map + ? JSON.parse(result.map.toString()) + : undefined return { code: result.css.toString(), + map, errors: [], deps } From 32090d99d267c0363c063671078f40ea20d5a17e Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 27 Feb 2022 20:47:55 +0900 Subject: [PATCH 03/27] feat(dev): less sourcemap --- .../vite/src/node/__tests__/plugins/css.spec.ts | 16 ++++++++++++++++ packages/vite/src/node/plugins/css.ts | 13 +++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 735eeb6ad6733e..50a987ba7334f5 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -166,6 +166,22 @@ describe('css source maps', () => { version: 3 } }, + { + name: 'less', + code: ` + .foo { + color: red; + } + `, + id: `${root}/foo.less`, + expectedMap: { + file: `${root}/foo.less`, + mappings: 'AACM;EACE', + names: [], + sources: [`${root}/foo.less`], + version: 3 + } + }, { name: 'scss module', code: ` diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index bf6bb01d476894..45e3c250c39443 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -767,7 +767,7 @@ async function compileCSS( map: { inline: false, annotation: false, - sourcesContent: false, + sourcesContent: false // when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources` // prev: preprocessorMap, } @@ -1222,7 +1222,11 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => { try { result = await nodeLess.render(source, { ...options, - plugins: [viteResolverPlugin, ...(options.plugins || [])] + plugins: [viteResolverPlugin, ...(options.plugins || [])], + sourceMap: { + outputSourceFiles: true, + sourceMapFileInline: false + } }) } catch (e) { const error = e as Less.RenderError @@ -1235,8 +1239,13 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => { } return { code: '', errors: [normalizedError], deps: [] } } + + const map: ExistingRawSourceMap = JSON.parse(result.map) + delete map.sourcesContent + return { code: result.css.toString(), + map, deps: result.imports, errors: [] } From 55077e3cb9315ce467e624912776f253ee7615cd Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 27 Feb 2022 21:12:39 +0900 Subject: [PATCH 04/27] feat(dev): stylus sourcemap --- .../src/node/__tests__/plugins/css.spec.ts | 15 +++++++++ packages/vite/src/node/plugins/css.ts | 33 +++++++++++++++++-- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 50a987ba7334f5..8d3e9abe48c212 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -182,6 +182,21 @@ describe('css source maps', () => { version: 3 } }, + { + name: 'stylus', + code: ` + .foo + color: red + `, + id: `${root}/foo.styl`, + expectedMap: { + file: `${root}/foo.styl`, + mappings: 'AACM;EACE,WAAO', + names: [], + sources: [`${root}/foo.styl`], + version: 3 + } + }, { name: 'scss module', code: ` diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 45e3c250c39443..6bc7807771d2d0 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1340,20 +1340,47 @@ const styl: StylePreprocessor = async (source, root, options) => { ) try { const ref = nodeStylus(source, options) - - // if (map) ref.set('sourcemap', { inline: false, comment: false }) + ref.set('sourcemap', { + comment: false, + inline: false, + basePath: root + }) const result = ref.render() // Concat imports deps with computed deps const deps = [...ref.deps(), ...importsDeps] - return { code: result, errors: [], deps } + // @ts-expect-error sourcemap exists + const map: ExistingRawSourceMap = ref.sourcemap + + return { + code: result, + map: formatStylusSourceMap(map, root), + errors: [], + deps + } } catch (e) { return { code: '', errors: [e], deps: [] } } } +function formatStylusSourceMap( + mapBefore: ExistingRawSourceMap, + root: string +): ExistingRawSourceMap { + const map = { ...mapBefore } + + const resolveFromRoot = (p: string) => normalizePath(path.resolve(root, p)) + + if (map.file) { + map.file = resolveFromRoot(map.file) + } + map.sources = map.sources.map(resolveFromRoot) + + return map +} + function getSource( source: string, filename: string, From 64742bef8442a7e3c1df2bc2967bf3949bd7f087 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Mon, 28 Feb 2022 03:31:54 +0900 Subject: [PATCH 05/27] dx: add css sourcemap debug output --- packages/vite/src/node/plugins/css.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 6bc7807771d2d0..9373c9f9434d97 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -51,6 +51,8 @@ import { addToHTMLProxyTransformResult } from './html' import type { RawSourceMap } from 'source-map-js' import { injectSourcesContent } from '../server/sourcemap' +const isDebug = process.env.DEBUG + // const debug = createDebugger('vite:css') export interface CSSOptions { @@ -307,11 +309,20 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { if (inlined) { return `export default ${JSON.stringify(css)}` } + + let cssContent = css const sourcemap = this.getCombinedSourcemap() await injectSourcesContent(sourcemap, cleanUrl(id), config.logger) - const cssContent = `${css}\n/*# sourceMappingURL=${genSourceMapUrl( + if (isDebug) { + cssContent += `\n/*${JSON.stringify(sourcemap, null, 2).replace( + /\*\//g, + '*\\/' + )}*/\n` + } + cssContent += `\n/*# sourceMappingURL=${genSourceMapUrl( sourcemap )} */` + return [ `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify( path.posix.join(config.base, CLIENT_PUBLIC_PATH) From 34f138d2114c44cbc0bc89e65901b3b6f7fe1b4e Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Mon, 28 Feb 2022 21:33:55 +0900 Subject: [PATCH 06/27] fix(dev): direct css request source map --- packages/vite/src/node/plugins/css.ts | 16 ++-------------- packages/vite/src/node/server/send.ts | 12 +++--------- packages/vite/src/node/server/sourcemap.ts | 21 ++++++++++++++++++++- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 9373c9f9434d97..4a46477de03f44 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -12,7 +12,6 @@ import { normalizePath, processSrcSet, parseRequest, - genSourceMapUrl, combineSourcemaps } from '../utils' import type { Plugin } from '../plugin' @@ -49,9 +48,7 @@ import type { ModuleNode } from '../server/moduleGraph' import { transform, formatMessages } from 'esbuild' import { addToHTMLProxyTransformResult } from './html' import type { RawSourceMap } from 'source-map-js' -import { injectSourcesContent } from '../server/sourcemap' - -const isDebug = process.env.DEBUG +import { injectSourcesContent, getCodeWithSourcemap } from '../server/sourcemap' // const debug = createDebugger('vite:css') @@ -310,18 +307,9 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { return `export default ${JSON.stringify(css)}` } - let cssContent = css const sourcemap = this.getCombinedSourcemap() await injectSourcesContent(sourcemap, cleanUrl(id), config.logger) - if (isDebug) { - cssContent += `\n/*${JSON.stringify(sourcemap, null, 2).replace( - /\*\//g, - '*\\/' - )}*/\n` - } - cssContent += `\n/*# sourceMappingURL=${genSourceMapUrl( - sourcemap - )} */` + const cssContent = getCodeWithSourcemap('css', css, sourcemap) return [ `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify( diff --git a/packages/vite/src/node/server/send.ts b/packages/vite/src/node/server/send.ts index 3523fbc7e971fe..bc36821ec0292d 100644 --- a/packages/vite/src/node/server/send.ts +++ b/packages/vite/src/node/server/send.ts @@ -1,9 +1,7 @@ import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'http' import getEtag from 'etag' import type { SourceMap } from 'rollup' -import { genSourceMapUrl } from '../utils' - -const isDebug = process.env.DEBUG +import { getCodeWithSourcemap } from './sourcemap' const alias: Record = { js: 'application/javascript', @@ -54,13 +52,9 @@ export function send( // inject source map reference if (map && map.mappings) { - if (isDebug) { - content += `\n/*${JSON.stringify(map, null, 2).replace( - /\*\//g, - '*\\/' - )}*/\n` + if (type === 'js' || type === 'css') { + content = getCodeWithSourcemap(type, content.toString(), map) } - content += `\n//# sourceMappingURL=${genSourceMapUrl(map)}` } res.statusCode = 200 diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index c6fc3b1f2579bf..90a0de6424f2bb 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -1,7 +1,8 @@ import path from 'path' import { promises as fs } from 'fs' import type { Logger } from '../logger' -import { createDebugger } from '../utils' +import { createDebugger, genSourceMapUrl } from '../utils' +import type { SourceMap } from 'rollup' const isDebug = !!process.env.DEBUG const debug = createDebugger('vite:sourcemap', { @@ -57,3 +58,21 @@ export async function injectSourcesContent( isDebug && debug(`Missing sources:\n ` + missingSources.join(`\n `)) } } + +export function getCodeWithSourcemap( + type: 'js' | 'css', + code: string, + map: SourceMap | null +) { + if (isDebug) { + code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n` + } + + if (type === 'js') { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map ?? undefined)}` + } else if (type === 'css') { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map ?? undefined)} */` + } + + return code +} From 31730b20643d6a6aba9a4c4d2660daed32a6af7c Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Thu, 3 Mar 2022 00:11:41 +0900 Subject: [PATCH 07/27] feat: vue sfc css sourcemap --- packages/playground/vue/PreProcessors.vue | 13 +++++++++++ packages/playground/vue/import.sass | 2 ++ packages/plugin-vue/src/index.ts | 3 ++- packages/plugin-vue/src/style.ts | 19 ++++++++++++--- packages/vite/src/node/index.ts | 1 + packages/vite/src/node/plugins/css.ts | 13 +++++++---- .../vite/src/node/server/pluginContainer.ts | 4 ++-- packages/vite/src/node/utils.ts | 23 +++++++++++++++++-- 8 files changed, 65 insertions(+), 13 deletions(-) create mode 100644 packages/playground/vue/import.sass diff --git a/packages/playground/vue/PreProcessors.vue b/packages/playground/vue/PreProcessors.vue index ddb636678e8cdd..79df8ba3e5f33e 100644 --- a/packages/playground/vue/PreProcessors.vue +++ b/packages/playground/vue/PreProcessors.vue @@ -9,6 +9,12 @@ p.pug-less p.pug-stylus | This is rendered from <template lang="pug"> | and styled with <style lang="stylus">. It should be orange. +p.pug-sass-import + | This is rendered from <template lang="pug"> + | and styled with <style lang="sass"> which has import. It should be blue. +p.pug-sass-non-import + | This is rendered from <template lang="pug"> + | and styled with <style lang="sass"> which has import. It should be yellow. SlotComponent template(v-slot:test-slot) div.pug-slot slot content @@ -42,3 +48,10 @@ color = orange .pug-stylus color: color + + diff --git a/packages/playground/vue/import.sass b/packages/playground/vue/import.sass new file mode 100644 index 00000000000000..e35f9085000fe1 --- /dev/null +++ b/packages/playground/vue/import.sass @@ -0,0 +1,2 @@ +.pug-sass-import + color: blue diff --git a/packages/plugin-vue/src/index.ts b/packages/plugin-vue/src/index.ts index fb1bce3cd61132..28a15996363285 100644 --- a/packages/plugin-vue/src/index.ts +++ b/packages/plugin-vue/src/index.ts @@ -235,7 +235,8 @@ export default function vuePlugin(rawOptions: Options = {}): Plugin { descriptor, Number(query.index), options, - this + this, + filename ) } } diff --git a/packages/plugin-vue/src/style.ts b/packages/plugin-vue/src/style.ts index ad9d981412f52d..5dba59e627922f 100644 --- a/packages/plugin-vue/src/style.ts +++ b/packages/plugin-vue/src/style.ts @@ -1,6 +1,7 @@ import type { SFCDescriptor } from 'vue/compiler-sfc' import type { TransformPluginContext } from 'rollup' import type { ResolvedOptions } from '.' +import { formatPostcssSourceMap } from 'vite' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export async function transformStyle( @@ -8,7 +9,8 @@ export async function transformStyle( descriptor: SFCDescriptor, index: number, options: ResolvedOptions, - pluginContext: TransformPluginContext + pluginContext: TransformPluginContext, + filename: string ) { const block = descriptor.styles[index] // vite already handles pre-processors and CSS module so this is only @@ -19,7 +21,14 @@ export async function transformStyle( id: `data-v-${descriptor.id}`, isProd: options.isProduction, source: code, - scoped: block.scoped + scoped: block.scoped, + postcssOptions: { + map: { + from: filename, + inline: false, + annotation: false + } + } }) if (result.errors.length) { @@ -36,8 +45,12 @@ export async function transformStyle( return null } + const map = result.map + ? formatPostcssSourceMap(result.map, filename) + : ({ mappings: '' } as any) + return { code: result.code, - map: result.map || ({ mappings: '' } as any) + map: map } } diff --git a/packages/vite/src/node/index.ts b/packages/vite/src/node/index.ts index aea96d14d758be..3286e9dffcbf04 100644 --- a/packages/vite/src/node/index.ts +++ b/packages/vite/src/node/index.ts @@ -5,6 +5,7 @@ export { build } from './build' export { optimizeDeps } from './optimizer' export { send } from './server/send' export { createLogger, printHttpServerUrls } from './logger' +export { formatPostcssSourceMap } from './plugins/css' export { transformWithEsbuild } from './plugins/esbuild' export { resolvePackageEntry } from './plugins/resolve' export { resolvePackageData } from './packages' diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 4a46477de03f44..96e8ac87129d89 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -761,8 +761,8 @@ async function compileCSS( .default(postcssPlugins) .process(code, { ...postcssOptions, - to: id, - from: id, + to: cleanUrl(id), + from: cleanUrl(id), map: { inline: false, annotation: false, @@ -812,9 +812,12 @@ async function compileCSS( } } - const postcssMap = formatPostcssSourceMap(postcssResult.map.toJSON(), id) + const postcssMap = formatPostcssSourceMap( + postcssResult.map.toJSON(), + cleanUrl(id) + ) const combinedMap = preprocessorMap - ? combineSourcemaps(id, [ + ? combineSourcemaps(cleanUrl(id), [ { ...postcssMap, version: 3 }, { ...preprocessorMap, version: 3 } ]) @@ -829,7 +832,7 @@ async function compileCSS( } } -function formatPostcssSourceMap( +export function formatPostcssSourceMap( rawMap: RawSourceMap, file: string ): ExistingRawSourceMap { diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index b5eca4b58dbf75..9828a0d5602ef8 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -50,7 +50,7 @@ import type { } from 'rollup' import * as acorn from 'acorn' import type { RawSourceMap } from '@ampproject/remapping/dist/types/types' -import { combineSourcemaps } from '../utils' +import { cleanUrl, combineSourcemaps } from '../utils' import MagicString from 'magic-string' import type { FSWatcher } from 'chokidar' import { @@ -420,7 +420,7 @@ export async function createPluginContainer( if (!combinedMap) { combinedMap = m as SourceMap } else { - combinedMap = combineSourcemaps(this.filename, [ + combinedMap = combineSourcemaps(cleanUrl(this.filename), [ { ...(m as RawSourceMap), sourcesContent: combinedMap.sourcesContent diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index b3483f8cd5dc26..fbfa45b4237b0e 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -543,6 +543,20 @@ export function combineSourcemaps( return { ...nullSourceMap } } + // FIXME: hack for parse broken with normalized absolute paths on windows (C:/path/to/something) + const base = normalizePath(path.dirname(filename)) + sourcemapList.forEach((sourcemap) => { + sourcemap.sources = sourcemap.sources.map((source) => { + if (!source) return null + if (sourcemap.sourceRoot) { + source = path.resolve(sourcemap.sourceRoot, source) + } + return normalizePath(path.relative(base, source)) + }) + sourcemap.sourceRoot = undefined + }) + const baseFilename = path.basename(filename) + // We don't declare type here so we can convert/fake/map as RawSourceMap let map //: SourceMap let mapIndex = 1 @@ -554,10 +568,10 @@ export function combineSourcemaps( map = remapping( sourcemapList[0], function loader(sourcefile) { - if (sourcefile === filename && sourcemapList[mapIndex]) { + if (sourcefile === baseFilename && sourcemapList[mapIndex]) { return sourcemapList[mapIndex++] } else { - return { ...nullSourceMap } + return null } }, true @@ -567,6 +581,11 @@ export function combineSourcemaps( delete map.file } + map.sources = map.sources.map((source) => + source ? normalizePath(path.resolve(base, source)) : null + ) + map.file = filename + return map as RawSourceMap } From 91d8bf58471a7151767dd69eb7e694e67e881924 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Thu, 3 Mar 2022 01:56:06 +0900 Subject: [PATCH 08/27] fix: css additional data sourcemap --- packages/vite/src/node/plugins/css.ts | 83 +++++++++++++++++++++------ 1 file changed, 65 insertions(+), 18 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 96e8ac87129d89..d1fd8fa8566b26 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -678,7 +678,12 @@ async function compileCSS( } code = preprocessResult.code - preprocessorMap = preprocessResult.map + preprocessorMap = combineSourcemapsIfExists( + opts.filename, + preprocessResult.map, + preprocessResult.additionalMap + ) + if (preprocessResult.deps) { preprocessResult.deps.forEach((dep) => { // sometimes sass registers the file itself as a dep @@ -816,17 +821,11 @@ async function compileCSS( postcssResult.map.toJSON(), cleanUrl(id) ) - const combinedMap = preprocessorMap - ? combineSourcemaps(cleanUrl(id), [ - { ...postcssMap, version: 3 }, - { ...preprocessorMap, version: 3 } - ]) - : postcssMap return { ast: postcssResult, code: postcssResult.css, - map: combinedMap as ExistingRawSourceMap, + map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap), modules, deps } @@ -854,6 +853,19 @@ export function formatPostcssSourceMap( } } +function combineSourcemapsIfExists( + filename: string, + map1: ExistingRawSourceMap | undefined, + map2: ExistingRawSourceMap | undefined +): ExistingRawSourceMap | undefined { + return map1 && map2 + ? (combineSourcemaps(filename, [ + { ...map1, version: 3 }, + { ...map2, version: 3 } + ]) as ExistingRawSourceMap) + : map1 +} + interface PostCSSConfigResult { options: Postcss.ProcessOptions plugins: Postcss.Plugin[] @@ -1053,6 +1065,7 @@ type SassStylePreprocessor = ( export interface StylePreprocessorResults { code: string map?: ExistingRawSourceMap | undefined + additionalMap?: ExistingRawSourceMap | undefined errors: RollupError[] deps: string[] } @@ -1117,9 +1130,14 @@ const scss: SassStylePreprocessor = async ( : importer.push(options.importer) } + const { content: data, map: additionalMap } = await getSource( + source, + options.filename, + options.additionalData + ) const finalOptions: Sass.Options = { ...options, - data: await getSource(source, options.filename, options.additionalData), + data, file: options.filename, outFile: options.filename, importer, @@ -1146,6 +1164,7 @@ const scss: SassStylePreprocessor = async ( return { code: result.css.toString(), map, + additionalMap, errors: [], deps } @@ -1218,11 +1237,15 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => { options.alias, resolvers ) - source = await getSource(source, options.filename, options.additionalData) + const { content, map: additionalMap } = await getSource( + source, + options.filename, + options.additionalData + ) let result: Less.RenderOutput | undefined try { - result = await nodeLess.render(source, { + result = await nodeLess.render(content, { ...options, plugins: [viteResolverPlugin, ...(options.plugins || [])], sourceMap: { @@ -1248,6 +1271,7 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => { return { code: result.css.toString(), map, + additionalMap, deps: result.imports, errors: [] } @@ -1329,7 +1353,7 @@ const styl: StylePreprocessor = async (source, root, options) => { const nodeStylus = loadPreprocessor(PreprocessLang.stylus, root) // Get source with preprocessor options.additionalData. Make sure a new line separator // is added to avoid any render error, as added stylus content may not have semi-colon separators - source = await getSource( + const { content, map: additionalMap } = await getSource( source, options.filename, options.additionalData, @@ -1341,7 +1365,7 @@ const styl: StylePreprocessor = async (source, root, options) => { path.resolve(dep) ) try { - const ref = nodeStylus(source, options) + const ref = nodeStylus(content, options) ref.set('sourcemap', { comment: false, inline: false, @@ -1359,6 +1383,7 @@ const styl: StylePreprocessor = async (source, root, options) => { return { code: result, map: formatStylusSourceMap(map, root), + additionalMap, errors: [], deps } @@ -1383,17 +1408,39 @@ function formatStylusSourceMap( return map } -function getSource( +async function getSource( source: string, filename: string, additionalData?: PreprocessorAdditionalData, sep: string = '' -): string | Promise { - if (!additionalData) return source +): Promise<{ content: string; map?: ExistingRawSourceMap }> { + if (!additionalData) return { content: source } if (typeof additionalData === 'function') { - return additionalData(source, filename) + const newContent = await additionalData(source, filename) + const ms = new MagicString(source) + ms.overwrite(0, source.length, newContent) + + return { + content: ms.toString(), + map: generateWithAbsoluteFilenameMap(ms, filename) + } + } + + const ms = new MagicString(source) + ms.appendLeft(0, sep) + ms.appendLeft(0, additionalData) + + return { + content: ms.toString(), + map: generateWithAbsoluteFilenameMap(ms, filename) } - return additionalData + sep + source +} + +function generateWithAbsoluteFilenameMap(ms: MagicString, filename: string) { + const map = ms.generateMap({ hires: true }) + map.file = filename + map.sources = [filename] + return map } const preProcessors = Object.freeze({ From 13c0bb6223c6b2aecae3934524943cce0d0753d3 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Fri, 4 Mar 2022 17:56:51 +0900 Subject: [PATCH 09/27] refactor: move genSourceMapUrl function --- packages/vite/src/node/server/sourcemap.ts | 9 ++++++++- packages/vite/src/node/utils.ts | 8 -------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/packages/vite/src/node/server/sourcemap.ts b/packages/vite/src/node/server/sourcemap.ts index 90a0de6424f2bb..68684a3c2d6f2a 100644 --- a/packages/vite/src/node/server/sourcemap.ts +++ b/packages/vite/src/node/server/sourcemap.ts @@ -1,7 +1,7 @@ import path from 'path' import { promises as fs } from 'fs' import type { Logger } from '../logger' -import { createDebugger, genSourceMapUrl } from '../utils' +import { createDebugger } from '../utils' import type { SourceMap } from 'rollup' const isDebug = !!process.env.DEBUG @@ -59,6 +59,13 @@ export async function injectSourcesContent( } } +function genSourceMapUrl(map: SourceMap | string | undefined) { + if (typeof map !== 'string') { + map = JSON.stringify(map) + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}` +} + export function getCodeWithSourcemap( type: 'js' | 'css', code: string, diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index fbfa45b4237b0e..2fb2d9aeed1589 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -21,7 +21,6 @@ import type { } from '@ampproject/remapping/dist/types/types' import { performance } from 'perf_hooks' import { parse as parseUrl, URLSearchParams } from 'url' -import type { SourceMap } from 'rollup' export function slash(p: string): string { return p.replace(/\\/g, '/') @@ -662,10 +661,3 @@ export function parseRequest(id: string): Record | null { } return Object.fromEntries(new URLSearchParams(search.slice(1))) } - -export function genSourceMapUrl(map: SourceMap | string | undefined) { - if (typeof map !== 'string') { - map = JSON.stringify(map) - } - return `data:application/json;base64,${Buffer.from(map).toString('base64')}` -} From 3e54315880dc6083e31d5aa56e1652cb092d03d4 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Fri, 4 Mar 2022 20:56:19 +0900 Subject: [PATCH 10/27] fix: better approach for windows hack --- packages/vite/src/node/utils.ts | 45 +++++++++++++++++++++++---------- pnpm-lock.yaml | 14 +++++----- 2 files changed, 39 insertions(+), 20 deletions(-) diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 2fb2d9aeed1589..6f5b785002b406 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -524,6 +524,26 @@ export async function processSrcSet( }, '') } +function escapeToLinuxLikePath(path: string) { + if (/^[A-Z]:/.test(path)) { + return path.replace(/^([A-Z]):\//, '/windows/$1/') + } + if (/^\/[^/]/.test(path)) { + return `/linux/${path}` + } + return path +} + +function unescapeToLinuxLikePath(path: string) { + if (path.startsWith('/linux/')) { + return path.slice('/linux'.length) + } + if (path.startsWith('/windows/')) { + return path.replace(/^\/windows\/([A-Z])\//, '$1:/') + } + return path +} + // based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 const nullSourceMap: RawSourceMap = { names: [], @@ -542,19 +562,17 @@ export function combineSourcemaps( return { ...nullSourceMap } } - // FIXME: hack for parse broken with normalized absolute paths on windows (C:/path/to/something) - const base = normalizePath(path.dirname(filename)) + // hack for parse broken with normalized absolute paths on windows (C:/path/to/something). + // escape them to linux like paths sourcemapList.forEach((sourcemap) => { - sourcemap.sources = sourcemap.sources.map((source) => { - if (!source) return null - if (sourcemap.sourceRoot) { - source = path.resolve(sourcemap.sourceRoot, source) - } - return normalizePath(path.relative(base, source)) - }) - sourcemap.sourceRoot = undefined + sourcemap.sources = sourcemap.sources.map((source) => + source ? escapeToLinuxLikePath(source) : null + ) + if (sourcemap.sourceRoot) { + sourcemap.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot) + } }) - const baseFilename = path.basename(filename) + const escapedFilename = escapeToLinuxLikePath(filename) // We don't declare type here so we can convert/fake/map as RawSourceMap let map //: SourceMap @@ -567,7 +585,7 @@ export function combineSourcemaps( map = remapping( sourcemapList[0], function loader(sourcefile) { - if (sourcefile === baseFilename && sourcemapList[mapIndex]) { + if (sourcefile === escapedFilename && sourcemapList[mapIndex]) { return sourcemapList[mapIndex++] } else { return null @@ -580,8 +598,9 @@ export function combineSourcemaps( delete map.file } + // unescape the previous hack map.sources = map.sources.map((source) => - source ? normalizePath(path.resolve(base, source)) : null + source ? unescapeToLinuxLikePath(source) : source ) map.file = filename diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ab2b4a7833c686..1801bb5bb2a141 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1976,9 +1976,9 @@ packages: chalk: 4.1.2 dev: true - /@jridgewell/resolve-uri/3.0.3: - resolution: {integrity: sha512-fuIOnc81C5iRNevb/XPiM8Khp9bVjreydRQ37rt0C/dY0PAW1DRvEM3WrKX/5rStS5lbgwS0FCgqSndh9tvK5w==} - engines: {node: '>=10.0.0'} + /@jridgewell/resolve-uri/3.0.5: + resolution: {integrity: sha512-VPeQ7+wH0itvQxnG+lIzWgkysKIr3L9sslimFW55rHMdGu/qCQ5z5h9zq4gI8uBtqkpHhsF4Z/OwExufUCThew==} + engines: {node: '>=6.0.0'} /@jridgewell/sourcemap-codec/1.4.10: resolution: {integrity: sha512-Ht8wIW5v165atIX1p+JvKR5ONzUyF4Ac8DZIQ5kZs9zrb6M8SJNXpx1zn04rn65VjBMygRoMXcyYwNK0fT7bEg==} @@ -1986,7 +1986,7 @@ packages: /@jridgewell/trace-mapping/0.3.2: resolution: {integrity: sha512-9KzzH4kMjA2XmBRHfqG2/Vtl7s92l6uNDd0wW7frDE+EUvQFGqNXhWp0UGJjSkt3v2AYjzOZn1QO9XaTNJIt1Q==} dependencies: - '@jridgewell/resolve-uri': 3.0.3 + '@jridgewell/resolve-uri': 3.0.5 '@jridgewell/sourcemap-codec': 1.4.10 /@mapbox/node-pre-gyp/1.0.8: @@ -3103,7 +3103,7 @@ packages: resolution: {integrity: sha512-oagLNqpfNv7CvmyMoexMDNyVDSiq1rya0AEUgcLlNHdHgNl6U/hi8xY370n5y+ZIFEXOx0J4B1qF2NDjMRxklA==} engines: {node: '>=6.0.0'} dependencies: - pvutils: 1.0.17 + pvutils: 1.1.3 dev: true /assert-never/1.2.1: @@ -7690,8 +7690,8 @@ packages: tslib: 2.3.1 dev: true - /pvutils/1.0.17: - resolution: {integrity: sha512-wLHYUQxWaXVQvKnwIDWFVKDJku9XDCvyhhxoq8dc5MFdIlRenyPI9eSfEtcvgHgD7FlvCyGAlWgOzRnZD99GZQ==} + /pvutils/1.1.3: + resolution: {integrity: sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==} engines: {node: '>=6.0.0'} dev: true From 215c9e9b12be92514796061f57e1249e6aa361c9 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 16:36:23 +0900 Subject: [PATCH 11/27] test: move sourcemap test --- packages/playground/vue/PreProcessors.vue | 13 -- packages/playground/vue/import.sass | 2 - .../src/node/__tests__/plugins/css.spec.ts | 127 ------------------ 3 files changed, 142 deletions(-) delete mode 100644 packages/playground/vue/import.sass diff --git a/packages/playground/vue/PreProcessors.vue b/packages/playground/vue/PreProcessors.vue index 79df8ba3e5f33e..ddb636678e8cdd 100644 --- a/packages/playground/vue/PreProcessors.vue +++ b/packages/playground/vue/PreProcessors.vue @@ -9,12 +9,6 @@ p.pug-less p.pug-stylus | This is rendered from <template lang="pug"> | and styled with <style lang="stylus">. It should be orange. -p.pug-sass-import - | This is rendered from <template lang="pug"> - | and styled with <style lang="sass"> which has import. It should be blue. -p.pug-sass-non-import - | This is rendered from <template lang="pug"> - | and styled with <style lang="sass"> which has import. It should be yellow. SlotComponent template(v-slot:test-slot) div.pug-slot slot content @@ -48,10 +42,3 @@ color = orange .pug-stylus color: color - - diff --git a/packages/playground/vue/import.sass b/packages/playground/vue/import.sass deleted file mode 100644 index e35f9085000fe1..00000000000000 --- a/packages/playground/vue/import.sass +++ /dev/null @@ -1,2 +0,0 @@ -.pug-sass-import - color: blue diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 8d3e9abe48c212..f25926437fb83f 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -115,130 +115,3 @@ describe('css path resolutions', () => { mockFs.mockReset() }) }) - -describe('css source maps', () => { - const root = normalizePath(process.cwd()) - const testcases = [ - { - name: 'cssmodule', - code: ` - .foo { - color: red; - } - `, - id: `${root}/foo.module.css`, - expectedMap: { - file: `${root}/foo.module.css`, - mappings: ';IACI;MACE,UAAU;IACZ', - names: [], - sources: [`${root}/foo.module.css`], - version: 3 - } - }, - { - name: 'sass', - code: ` - .foo - color: red - `, - id: `${root}/foo.sass`, - expectedMap: { - file: `${root}/foo.sass`, - mappings: 'AACI;EACE', - names: [], - sources: [`${root}/foo.sass`], - version: 3 - } - }, - { - name: 'scss', - code: ` - .foo { - color: red; - } - `, - id: `${root}/foo.scss`, - expectedMap: { - file: `${root}/foo.scss`, - mappings: 'AACM;EACE', - names: [], - sources: [`${root}/foo.scss`], - version: 3 - } - }, - { - name: 'less', - code: ` - .foo { - color: red; - } - `, - id: `${root}/foo.less`, - expectedMap: { - file: `${root}/foo.less`, - mappings: 'AACM;EACE', - names: [], - sources: [`${root}/foo.less`], - version: 3 - } - }, - { - name: 'stylus', - code: ` - .foo - color: red - `, - id: `${root}/foo.styl`, - expectedMap: { - file: `${root}/foo.styl`, - mappings: 'AACM;EACE,WAAO', - names: [], - sources: [`${root}/foo.styl`], - version: 3 - } - }, - { - name: 'scss module', - code: ` - .foo { - color: red; - } - `, - id: `${root}/foo.module.scss`, - expectedMap: { - file: `${root}/foo.module.scss`, - mappings: 'AACM;EACE', - names: [], - sources: [`${root}/foo.module.scss`], - version: 3 - } - } - ] - - test.concurrent.each(testcases)( - '$name', - async ({ code, id, expectedMap }) => { - const config = await resolveConfig( - { - root - }, - 'serve' - ) - const { transform, buildStart } = cssPlugin(config) - - await buildStart.call({}) - - const { map } = await transform.call( - { - addWatchFile() { - return - } - }, - code, - id - ) - - expect(map).toMatchObject(expectedMap) - } - ) -}) From 287cceb10bf695b2cc51ff88f0f5b3c8d456d430 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 15:19:27 +0900 Subject: [PATCH 12/27] test: css sourcemap --- .../__snapshots__/serve.spec.ts.snap | 46 ++++++++++++ .../css-sourcemap/__tests__/serve.spec.ts | 74 +++++++++++++++++++ .../playground/css-sourcemap/be-imported.css | 3 + .../css-sourcemap/imported-with-import.css | 5 ++ .../playground/css-sourcemap/imported.css | 3 + packages/playground/css-sourcemap/index.html | 17 +++++ .../css-sourcemap/linked-with-import.css | 5 ++ packages/playground/css-sourcemap/linked.css | 3 + .../playground/css-sourcemap/package.json | 17 +++++ .../playground/css-sourcemap/vite.config.js | 10 +++ pnpm-lock.yaml | 21 ++++-- 11 files changed, 197 insertions(+), 7 deletions(-) create mode 100644 packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap create mode 100644 packages/playground/css-sourcemap/__tests__/serve.spec.ts create mode 100644 packages/playground/css-sourcemap/be-imported.css create mode 100644 packages/playground/css-sourcemap/imported-with-import.css create mode 100644 packages/playground/css-sourcemap/imported.css create mode 100644 packages/playground/css-sourcemap/index.html create mode 100644 packages/playground/css-sourcemap/linked-with-import.css create mode 100644 packages/playground/css-sourcemap/linked.css create mode 100644 packages/playground/css-sourcemap/package.json create mode 100644 packages/playground/css-sourcemap/vite.config.js diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap new file mode 100644 index 00000000000000..c3fe0993a143ec --- /dev/null +++ b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -0,0 +1,46 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`imported css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; + +exports[`imported css with import: sourcesContent 1`] = ` +Array [ + ".be-imported { + color: red; +} +", + "@import '@/be-imported.css'; + +.imported-with-import { + color: red; +} +", +] +`; + +exports[`imported css: mappings 1`] = `"AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACb,CAAC;"`; + +exports[`imported css: sourcesContent 1`] = ` +Array [ + ".imported { + color: red; +} +", +] +`; + +exports[`linked css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; + +exports[`linked css with import: sourcesContent 1`] = ` +Array [ + ".be-imported { + color: red; +} +", + "@import '@/be-imported.css'; + +.linked-with-import { + color: red; +} +", +] +`; diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts new file mode 100644 index 00000000000000..2605f0810c9f1f --- /dev/null +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -0,0 +1,74 @@ +import { fromComment } from 'convert-source-map' +import { URL } from 'url' +import { normalizePath } from 'vite' +import { isBuild, testDir } from 'testUtils' + +if (!isBuild) { + const root = normalizePath(testDir) + + const getStyleTagContentIncluding = async (content: string) => { + const styles = await page.$$('style') + for (const style of styles) { + const text = await style.textContent() + if (text.includes(content)) { + return text + } + } + throw new Error('Not found') + } + + const extractSourcemap = (content: string) => + fromComment(content.trim().split('\n').at(-1)).toObject() + + const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { + expect(map.sources).toStrictEqual(sources) + expect(map.mappings).toMatchSnapshot('mappings') + expect(map.sourcesContent).toMatchSnapshot('sourcesContent') + } + + test('linked css', async () => { + const res = await page.request.get( + new URL('./linked.css', page.url()).href, + { + headers: { + accept: 'text/css' + } + } + ) + const css = await res.text() + const lastLine = css.split('\n').at(-1) + expect(lastLine.includes('/*')).toBe(false) // expect no sourcemap + }) + + test('linked css with import', async () => { + const res = await page.request.get( + new URL('./linked-with-import.css', page.url()).href, + { + headers: { + accept: 'text/css' + } + } + ) + const css = await res.text() + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/be-imported.css`, `${root}/linked-with-import.css`] + }) + }) + + test('imported css', async () => { + const css = await getStyleTagContentIncluding('.imported ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/imported.css`] + }) + }) + + test('imported css with import', async () => { + const css = await getStyleTagContentIncluding('.imported-with-import ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/be-imported.css`, `${root}/imported-with-import.css`] + }) + }) +} diff --git a/packages/playground/css-sourcemap/be-imported.css b/packages/playground/css-sourcemap/be-imported.css new file mode 100644 index 00000000000000..a29e5f77e3cb5d --- /dev/null +++ b/packages/playground/css-sourcemap/be-imported.css @@ -0,0 +1,3 @@ +.be-imported { + color: red; +} diff --git a/packages/playground/css-sourcemap/imported-with-import.css b/packages/playground/css-sourcemap/imported-with-import.css new file mode 100644 index 00000000000000..6a1ed3c3772698 --- /dev/null +++ b/packages/playground/css-sourcemap/imported-with-import.css @@ -0,0 +1,5 @@ +@import '@/be-imported.css'; + +.imported-with-import { + color: red; +} diff --git a/packages/playground/css-sourcemap/imported.css b/packages/playground/css-sourcemap/imported.css new file mode 100644 index 00000000000000..9c9b32924962dc --- /dev/null +++ b/packages/playground/css-sourcemap/imported.css @@ -0,0 +1,3 @@ +.imported { + color: red; +} diff --git a/packages/playground/css-sourcemap/index.html b/packages/playground/css-sourcemap/index.html new file mode 100644 index 00000000000000..f58cf45b4e7a44 --- /dev/null +++ b/packages/playground/css-sourcemap/index.html @@ -0,0 +1,17 @@ + + + +
+

CSS Sourcemap

+ +

<linked>: no import

+

<linked>: with import

+ +

<imported>: no import

+

<imported>: with import

+
+ + diff --git a/packages/playground/css-sourcemap/linked-with-import.css b/packages/playground/css-sourcemap/linked-with-import.css new file mode 100644 index 00000000000000..6f65d92441fa49 --- /dev/null +++ b/packages/playground/css-sourcemap/linked-with-import.css @@ -0,0 +1,5 @@ +@import '@/be-imported.css'; + +.linked-with-import { + color: red; +} diff --git a/packages/playground/css-sourcemap/linked.css b/packages/playground/css-sourcemap/linked.css new file mode 100644 index 00000000000000..e3b67c83872ac0 --- /dev/null +++ b/packages/playground/css-sourcemap/linked.css @@ -0,0 +1,3 @@ +.linked { + color: red; +} diff --git a/packages/playground/css-sourcemap/package.json b/packages/playground/css-sourcemap/package.json new file mode 100644 index 00000000000000..2d71c4fcc29cfc --- /dev/null +++ b/packages/playground/css-sourcemap/package.json @@ -0,0 +1,17 @@ +{ + "name": "test-css-sourcemap", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../vite/bin/vite", + "preview": "vite preview" + }, + "devDependencies": { + "convert-source-map": "^1.8.0", + "less": "^4.1.2", + "sass": "^1.43.4", + "stylus": "^0.55.0" + } +} diff --git a/packages/playground/css-sourcemap/vite.config.js b/packages/playground/css-sourcemap/vite.config.js new file mode 100644 index 00000000000000..30e93f5312bd75 --- /dev/null +++ b/packages/playground/css-sourcemap/vite.config.js @@ -0,0 +1,10 @@ +/** + * @type {import('vite').UserConfig} + */ +module.exports = { + resolve: { + alias: { + '@': __dirname + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1801bb5bb2a141..aec009e47f1c76 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,18 @@ importers: packages/playground/css-codesplit-cjs: specifiers: {} + packages/playground/css-sourcemap: + specifiers: + convert-source-map: ^1.8.0 + less: ^4.1.2 + sass: ^1.43.4 + stylus: ^0.55.0 + devDependencies: + convert-source-map: 1.8.0 + less: 4.1.2 + sass: 1.45.1 + stylus: 0.55.0 + packages/playground/css/css-dep: specifiers: {} @@ -8078,9 +8090,9 @@ packages: engines: {node: '>=8.9.0'} hasBin: true dependencies: - chokidar: 3.5.2 + chokidar: 3.5.3 immutable: 4.0.0 - source-map-js: 1.0.1 + source-map-js: 1.0.2 dev: true /sax/1.2.4: @@ -8292,11 +8304,6 @@ packages: smart-buffer: 4.2.0 dev: true - /source-map-js/1.0.1: - resolution: {integrity: sha512-4+TN2b3tqOCd/kaGRJ/sTYA0tR0mdXx26ipdolxcwtJVqEnqNYvlCAt1q3ypy4QMlYus+Zh34RNtYLoq2oQ4IA==} - engines: {node: '>=0.10.0'} - dev: true - /source-map-js/1.0.2: resolution: {integrity: sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==} engines: {node: '>=0.10.0'} From e041930a7d6e12b5e783d8060e1f64f072c8d3d6 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 15:58:26 +0900 Subject: [PATCH 13/27] test: sass sourcemap --- .../__snapshots__/serve.spec.ts.snap | 22 +++++++++++++++++++ .../css-sourcemap/__tests__/serve.spec.ts | 16 ++++++++++++++ .../css-sourcemap/imported.module.sass | 3 +++ .../playground/css-sourcemap/imported.sass | 3 +++ packages/playground/css-sourcemap/index.html | 9 ++++++++ 5 files changed, 53 insertions(+) create mode 100644 packages/playground/css-sourcemap/imported.module.sass create mode 100644 packages/playground/css-sourcemap/imported.sass diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap index c3fe0993a143ec..4008102a169a63 100644 --- a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -28,6 +28,28 @@ Array [ ] `; +exports[`imported sass module: mappings 1`] = `"AACE;EACE"`; + +exports[`imported sass module: sourcesContent 1`] = ` +Array [ + ".imported + &-sass-module + color: red +", +] +`; + +exports[`imported sass: mappings 1`] = `"AACE;EACE"`; + +exports[`imported sass: sourcesContent 1`] = ` +Array [ + ".imported + &-sass + color: red +", +] +`; + exports[`linked css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; exports[`linked css with import: sourcesContent 1`] = ` diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 2605f0810c9f1f..3a1889d97c33ef 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -71,4 +71,20 @@ if (!isBuild) { sources: [`${root}/be-imported.css`, `${root}/imported-with-import.css`] }) }) + + test('imported sass', async () => { + const css = await getStyleTagContentIncluding('.imported-sass ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/imported.sass`] + }) + }) + + test('imported sass module', async () => { + const css = await getStyleTagContentIncluding('._imported-sass-module_') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/imported.module.sass`] + }) + }) } diff --git a/packages/playground/css-sourcemap/imported.module.sass b/packages/playground/css-sourcemap/imported.module.sass new file mode 100644 index 00000000000000..448a5e7e31f75a --- /dev/null +++ b/packages/playground/css-sourcemap/imported.module.sass @@ -0,0 +1,3 @@ +.imported + &-sass-module + color: red diff --git a/packages/playground/css-sourcemap/imported.sass b/packages/playground/css-sourcemap/imported.sass new file mode 100644 index 00000000000000..06fa634d5dd4e9 --- /dev/null +++ b/packages/playground/css-sourcemap/imported.sass @@ -0,0 +1,3 @@ +.imported + &-sass + color: red diff --git a/packages/playground/css-sourcemap/index.html b/packages/playground/css-sourcemap/index.html index f58cf45b4e7a44..7f346d6caef503 100644 --- a/packages/playground/css-sourcemap/index.html +++ b/packages/playground/css-sourcemap/index.html @@ -9,9 +9,18 @@

CSS Sourcemap

<imported>: no import

<imported>: with import

+ +

<imported sass>

+

<imported sass> with module

From 5201c1ff097ae23018646b285e124a71451f11fe Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 16:06:41 +0900 Subject: [PATCH 14/27] test: less sourcemap --- .../__tests__/__snapshots__/serve.spec.ts.snap | 13 +++++++++++++ .../css-sourcemap/__tests__/serve.spec.ts | 8 ++++++++ packages/playground/css-sourcemap/imported.less | 5 +++++ packages/playground/css-sourcemap/index.html | 8 ++++++-- 4 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 packages/playground/css-sourcemap/imported.less diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap index 4008102a169a63..12549e59ce8887 100644 --- a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -28,6 +28,19 @@ Array [ ] `; +exports[`imported less: mappings 1`] = `"AACE;EACE"`; + +exports[`imported less: sourcesContent 1`] = ` +Array [ + ".imported { + &-less { + color: red; + } +} +", +] +`; + exports[`imported sass module: mappings 1`] = `"AACE;EACE"`; exports[`imported sass module: sourcesContent 1`] = ` diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 3a1889d97c33ef..c8c27316241fb9 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -87,4 +87,12 @@ if (!isBuild) { sources: [`${root}/imported.module.sass`] }) }) + + test('imported less', async () => { + const css = await getStyleTagContentIncluding('.imported-less ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/imported.less`] + }) + }) } diff --git a/packages/playground/css-sourcemap/imported.less b/packages/playground/css-sourcemap/imported.less new file mode 100644 index 00000000000000..cde154a6508e43 --- /dev/null +++ b/packages/playground/css-sourcemap/imported.less @@ -0,0 +1,5 @@ +.imported { + &-less { + color: red; + } +} diff --git a/packages/playground/css-sourcemap/index.html b/packages/playground/css-sourcemap/index.html index 7f346d6caef503..598f8cc3dc588a 100644 --- a/packages/playground/css-sourcemap/index.html +++ b/packages/playground/css-sourcemap/index.html @@ -12,6 +12,8 @@

CSS Sourcemap

<imported sass>

<imported sass> with module

+ +

<imported less>

From 6f7569b4037d24c921e8f4e9c1da16120e61a8b5 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 16:10:32 +0900 Subject: [PATCH 15/27] test: stylus sourcemap --- .../__tests__/__snapshots__/serve.spec.ts.snap | 11 +++++++++++ .../playground/css-sourcemap/__tests__/serve.spec.ts | 8 ++++++++ packages/playground/css-sourcemap/imported.styl | 3 +++ packages/playground/css-sourcemap/index.html | 5 +++++ 4 files changed, 27 insertions(+) create mode 100644 packages/playground/css-sourcemap/imported.styl diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap index 12549e59ce8887..172f728fc3746d 100644 --- a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -63,6 +63,17 @@ Array [ ] `; +exports[`imported stylus: mappings 1`] = `"AACE;EACE,WAAM"`; + +exports[`imported stylus: sourcesContent 1`] = ` +Array [ + ".imported + &-stylus + color red +", +] +`; + exports[`linked css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; exports[`linked css with import: sourcesContent 1`] = ` diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index c8c27316241fb9..f8c622ad315652 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -95,4 +95,12 @@ if (!isBuild) { sources: [`${root}/imported.less`] }) }) + + test('imported stylus', async () => { + const css = await getStyleTagContentIncluding('.imported-stylus ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/imported.styl`] + }) + }) } diff --git a/packages/playground/css-sourcemap/imported.styl b/packages/playground/css-sourcemap/imported.styl new file mode 100644 index 00000000000000..ad3a5e4bf8141f --- /dev/null +++ b/packages/playground/css-sourcemap/imported.styl @@ -0,0 +1,3 @@ +.imported + &-stylus + color red diff --git a/packages/playground/css-sourcemap/index.html b/packages/playground/css-sourcemap/index.html index 598f8cc3dc588a..f8d12582a50ce8 100644 --- a/packages/playground/css-sourcemap/index.html +++ b/packages/playground/css-sourcemap/index.html @@ -14,6 +14,8 @@

CSS Sourcemap

<imported sass> with module

<imported less>

+ +

<imported stylus>

From f3d446163a9039c0360777b3366f960dae37d101 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 16:32:18 +0900 Subject: [PATCH 16/27] test: css additional data sourcemap --- .../__tests__/__snapshots__/serve.spec.ts.snap | 2 +- packages/playground/css-sourcemap/imported.less | 2 +- packages/playground/css-sourcemap/index.html | 6 +++--- packages/playground/css-sourcemap/vite.config.js | 7 +++++++ 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap index 172f728fc3746d..60bb675fb43ace 100644 --- a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -34,7 +34,7 @@ exports[`imported less: sourcesContent 1`] = ` Array [ ".imported { &-less { - color: red; + color: @color; } } ", diff --git a/packages/playground/css-sourcemap/imported.less b/packages/playground/css-sourcemap/imported.less index cde154a6508e43..e71b15eb102441 100644 --- a/packages/playground/css-sourcemap/imported.less +++ b/packages/playground/css-sourcemap/imported.less @@ -1,5 +1,5 @@ .imported { &-less { - color: red; + color: @color; } } diff --git a/packages/playground/css-sourcemap/index.html b/packages/playground/css-sourcemap/index.html index f8d12582a50ce8..2fedceb8f2be44 100644 --- a/packages/playground/css-sourcemap/index.html +++ b/packages/playground/css-sourcemap/index.html @@ -13,7 +13,7 @@

CSS Sourcemap

<imported sass>

<imported sass> with module

-

<imported less>

+

<imported less> with string additionalData

<imported stylus>

@@ -26,8 +26,8 @@

CSS Sourcemap

import sassModule from './imported.module.sass' document - .querySelector('.imported-sass-module') - .classList.add(sassModule['imported-sass-module']) + .querySelector('.imported-sass-module') + .classList.add(sassModule['imported-sass-module']) import './imported.less' diff --git a/packages/playground/css-sourcemap/vite.config.js b/packages/playground/css-sourcemap/vite.config.js index 30e93f5312bd75..764aaaa100f773 100644 --- a/packages/playground/css-sourcemap/vite.config.js +++ b/packages/playground/css-sourcemap/vite.config.js @@ -6,5 +6,12 @@ module.exports = { alias: { '@': __dirname } + }, + css: { + preprocessorOptions: { + less: { + additionalData: '@color: red;' + } + } } } From da08d1955ec70dbfcafaf9003f51113636f6461b Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 17:09:03 +0900 Subject: [PATCH 17/27] test: vue sfc style sourcemap --- packages/playground/vue-sourcemap/Css.vue | 23 +++ packages/playground/vue-sourcemap/Less.vue | 9 + packages/playground/vue-sourcemap/Main.vue | 16 ++ packages/playground/vue-sourcemap/Sass.vue | 8 + .../vue-sourcemap/SassWithImport.vue | 11 ++ .../__snapshots__/serve.spec.ts.snap | 175 ++++++++++++++++++ .../vue-sourcemap/__tests__/serve.spec.ts | 97 ++++++++++ packages/playground/vue-sourcemap/index.html | 7 + .../playground/vue-sourcemap/package.json | 20 ++ .../vue-sourcemap/sassWithImportImported.sass | 2 + .../vue-sourcemap/src-import/SrcImport.vue | 8 + .../src-import/src-import-imported.sass | 2 + .../vue-sourcemap/src-import/src-import.css | 3 + .../vue-sourcemap/src-import/src-import.sass | 4 + .../playground/vue-sourcemap/vite.config.js | 15 ++ pnpm-lock.yaml | 109 +++++++++++ 16 files changed, 509 insertions(+) create mode 100644 packages/playground/vue-sourcemap/Css.vue create mode 100644 packages/playground/vue-sourcemap/Less.vue create mode 100644 packages/playground/vue-sourcemap/Main.vue create mode 100644 packages/playground/vue-sourcemap/Sass.vue create mode 100644 packages/playground/vue-sourcemap/SassWithImport.vue create mode 100644 packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap create mode 100644 packages/playground/vue-sourcemap/__tests__/serve.spec.ts create mode 100644 packages/playground/vue-sourcemap/index.html create mode 100644 packages/playground/vue-sourcemap/package.json create mode 100644 packages/playground/vue-sourcemap/sassWithImportImported.sass create mode 100644 packages/playground/vue-sourcemap/src-import/SrcImport.vue create mode 100644 packages/playground/vue-sourcemap/src-import/src-import-imported.sass create mode 100644 packages/playground/vue-sourcemap/src-import/src-import.css create mode 100644 packages/playground/vue-sourcemap/src-import/src-import.sass create mode 100644 packages/playground/vue-sourcemap/vite.config.js diff --git a/packages/playground/vue-sourcemap/Css.vue b/packages/playground/vue-sourcemap/Css.vue new file mode 100644 index 00000000000000..19668de8d33965 --- /dev/null +++ b/packages/playground/vue-sourcemap/Css.vue @@ -0,0 +1,23 @@ + + + + + + + diff --git a/packages/playground/vue-sourcemap/Less.vue b/packages/playground/vue-sourcemap/Less.vue new file mode 100644 index 00000000000000..f12a3e55f2111c --- /dev/null +++ b/packages/playground/vue-sourcemap/Less.vue @@ -0,0 +1,9 @@ + + + diff --git a/packages/playground/vue-sourcemap/Main.vue b/packages/playground/vue-sourcemap/Main.vue new file mode 100644 index 00000000000000..04ddf50071ccb3 --- /dev/null +++ b/packages/playground/vue-sourcemap/Main.vue @@ -0,0 +1,16 @@ + + + diff --git a/packages/playground/vue-sourcemap/Sass.vue b/packages/playground/vue-sourcemap/Sass.vue new file mode 100644 index 00000000000000..0fded031a52c72 --- /dev/null +++ b/packages/playground/vue-sourcemap/Sass.vue @@ -0,0 +1,8 @@ + + + diff --git a/packages/playground/vue-sourcemap/SassWithImport.vue b/packages/playground/vue-sourcemap/SassWithImport.vue new file mode 100644 index 00000000000000..7a00420a00bb3a --- /dev/null +++ b/packages/playground/vue-sourcemap/SassWithImport.vue @@ -0,0 +1,11 @@ + + + diff --git a/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap new file mode 100644 index 00000000000000..a11f3642190d4d --- /dev/null +++ b/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap @@ -0,0 +1,175 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`css module: mappings 1`] = `";AAaA;EACE,UAAU;AACZ"`; + +exports[`css module: sourcesContent 1`] = ` +Array [ + " + + + + + + +", +] +`; + +exports[`css scoped: mappings 1`] = `";AAmBA;EACE,UAAU;AACZ"`; + +exports[`css scoped: sourcesContent 1`] = ` +Array [ + " + + + + + + +", +] +`; + +exports[`css: mappings 1`] = `";AAOA;EACE,UAAU;AACZ"`; + +exports[`css: sourcesContent 1`] = ` +Array [ + " + + + + + + +", +] +`; + +exports[`less with additionalData: mappings 1`] = `"AAKA;EACE"`; + +exports[`less with additionalData: sourcesContent 1`] = ` +Array [ + " + + +", +] +`; + +exports[`sass with import: mappings 1`] = `"AAAA;EACE;;ACOF;EACE"`; + +exports[`sass with import: sourcesContent 1`] = ` +Array [ + ".sass-with-import-imported + color: red +", + " + + +", +] +`; + +exports[`sass: mappings 1`] = `"AAKA;EACE"`; + +exports[`sass: sourcesContent 1`] = ` +Array [ + " + + +", +] +`; + +exports[`src imported sass: mappings 1`] = `"AAAA;EACE;;ACCF;EACE"`; + +exports[`src imported sass: sourcesContent 1`] = ` +Array [ + ".src-import-sass-imported + color: red +", + "@import './src-import-imported' + +.src-import-sass + color: red +", +] +`; + +exports[`src imported: mappings 1`] = `"AAAA;EACE,UAAU;AACZ"`; + +exports[`src imported: sourcesContent 1`] = ` +Array [ + ".src-import { + color: red; +} +", +] +`; diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts new file mode 100644 index 00000000000000..973bc430610c4a --- /dev/null +++ b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -0,0 +1,97 @@ +import { fromComment } from 'convert-source-map' +import { normalizePath } from 'vite' +import { isBuild, testDir } from 'testUtils' + +if (!isBuild) { + const root = normalizePath(testDir) + + const getStyleTagContentIncluding = async (content: string) => { + const styles = await page.$$('style') + for (const style of styles) { + const text = await style.textContent() + if (text.includes(content)) { + return text + } + } + throw new Error('Not found') + } + + const extractSourcemap = (content: string) => + fromComment(content.trim().split('\n').at(-1)).toObject() + + const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { + expect(map.sources).toStrictEqual(sources) + expect(map.mappings).toMatchSnapshot('mappings') + expect(map.sourcesContent).toMatchSnapshot('sourcesContent') + } + + test('css', async () => { + const css = await getStyleTagContentIncluding('.css ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/Css.vue`] + }) + }) + + test('css module', async () => { + const css = await getStyleTagContentIncluding('._css-module_') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/Css.vue`] + }) + }) + + test('css scoped', async () => { + const css = await getStyleTagContentIncluding('.css-scoped[data-v-') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/Css.vue`] + }) + }) + + test('sass', async () => { + const css = await getStyleTagContentIncluding('.sass ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/Sass.vue`] + }) + }) + + test('sass with import', async () => { + const css = await getStyleTagContentIncluding('.sass-with-import ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [ + `${root}/sassWithImportImported.sass`, + `${root}/SassWithImport.vue` + ] + }) + }) + + test('less with additionalData', async () => { + const css = await getStyleTagContentIncluding('.less ') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/Less.vue`] + }) + }) + + test('src imported', async () => { + const css = await getStyleTagContentIncluding('.src-import[data-v-') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [`${root}/src-import/src-import.css`] + }) + }) + + test('src imported sass', async () => { + const css = await getStyleTagContentIncluding('.src-import-sass[data-v-') + const map = extractSourcemap(css) + assertSourcemap(map, { + sources: [ + `${root}/src-import/src-import-imported.sass`, + `${root}/src-import/src-import.sass` + ] + }) + }) +} diff --git a/packages/playground/vue-sourcemap/index.html b/packages/playground/vue-sourcemap/index.html new file mode 100644 index 00000000000000..57f325518a2c25 --- /dev/null +++ b/packages/playground/vue-sourcemap/index.html @@ -0,0 +1,7 @@ +
+ diff --git a/packages/playground/vue-sourcemap/package.json b/packages/playground/vue-sourcemap/package.json new file mode 100644 index 00000000000000..5672b5e3d9d57d --- /dev/null +++ b/packages/playground/vue-sourcemap/package.json @@ -0,0 +1,20 @@ +{ + "name": "test-vue-sourcemap", + "private": true, + "version": "0.0.0", + "scripts": { + "dev": "vite", + "build": "vite build", + "debug": "node --inspect-brk ../../vite/bin/vite", + "preview": "vite preview" + }, + "devDependencies": { + "@vitejs/plugin-vue": "workspace:*", + "convert-source-map": "^1.8.0", + "less": "^4.1.2", + "sass": "^1.43.4" + }, + "dependencies": { + "vue": "^3.2.31" + } +} diff --git a/packages/playground/vue-sourcemap/sassWithImportImported.sass b/packages/playground/vue-sourcemap/sassWithImportImported.sass new file mode 100644 index 00000000000000..8092b37048cbdd --- /dev/null +++ b/packages/playground/vue-sourcemap/sassWithImportImported.sass @@ -0,0 +1,2 @@ +.sass-with-import-imported + color: red diff --git a/packages/playground/vue-sourcemap/src-import/SrcImport.vue b/packages/playground/vue-sourcemap/src-import/SrcImport.vue new file mode 100644 index 00000000000000..406c6a6b45382d --- /dev/null +++ b/packages/playground/vue-sourcemap/src-import/SrcImport.vue @@ -0,0 +1,8 @@ + + + + diff --git a/packages/playground/vue-sourcemap/src-import/src-import-imported.sass b/packages/playground/vue-sourcemap/src-import/src-import-imported.sass new file mode 100644 index 00000000000000..2ed87d933e58a6 --- /dev/null +++ b/packages/playground/vue-sourcemap/src-import/src-import-imported.sass @@ -0,0 +1,2 @@ +.src-import-sass-imported + color: red diff --git a/packages/playground/vue-sourcemap/src-import/src-import.css b/packages/playground/vue-sourcemap/src-import/src-import.css new file mode 100644 index 00000000000000..da61ff0fb6cb27 --- /dev/null +++ b/packages/playground/vue-sourcemap/src-import/src-import.css @@ -0,0 +1,3 @@ +.src-import { + color: red; +} diff --git a/packages/playground/vue-sourcemap/src-import/src-import.sass b/packages/playground/vue-sourcemap/src-import/src-import.sass new file mode 100644 index 00000000000000..c7e0314fda541c --- /dev/null +++ b/packages/playground/vue-sourcemap/src-import/src-import.sass @@ -0,0 +1,4 @@ +@import './src-import-imported' + +.src-import-sass + color: red diff --git a/packages/playground/vue-sourcemap/vite.config.js b/packages/playground/vue-sourcemap/vite.config.js new file mode 100644 index 00000000000000..0347aa84a43a1c --- /dev/null +++ b/packages/playground/vue-sourcemap/vite.config.js @@ -0,0 +1,15 @@ +const vuePlugin = require('@vitejs/plugin-vue') + +/** + * @type {import('vite').UserConfig} + */ +module.exports = { + css: { + preprocessorOptions: { + less: { + additionalData: '@color: red;' + } + } + }, + plugins: [vuePlugin()] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index aec009e47f1c76..3da7c0fb6b9cb6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -668,6 +668,21 @@ importers: devDependencies: '@vitejs/plugin-vue': link:../../plugin-vue + packages/playground/vue-sourcemap: + specifiers: + '@vitejs/plugin-vue': workspace:* + convert-source-map: ^1.8.0 + less: ^4.1.2 + sass: ^1.43.4 + vue: ^3.2.31 + dependencies: + vue: 3.2.31 + devDependencies: + '@vitejs/plugin-vue': link:../../plugin-vue + convert-source-map: 1.8.0 + less: 4.1.2 + sass: 1.45.1 + packages/playground/wasm: specifiers: {} @@ -2672,6 +2687,15 @@ packages: source-map: 0.6.1 dev: true + /@vue/compiler-core/3.2.31: + resolution: {integrity: sha512-aKno00qoA4o+V/kR6i/pE+aP+esng5siNAVQ422TkBNM6qA4veXiZbSe8OTXHXquEi/f6Akc+nLfB4JGfe4/WQ==} + dependencies: + '@babel/parser': 7.17.0 + '@vue/shared': 3.2.31 + estree-walker: 2.0.2 + source-map: 0.6.1 + dev: false + /@vue/compiler-dom/3.2.26: resolution: {integrity: sha512-smBfaOW6mQDxcT3p9TKT6mE22vjxjJL50GFVJiI0chXYGU/xzC05QRGrW3HHVuJrmLTLx5zBhsZ2dIATERbarg==} dependencies: @@ -2692,6 +2716,13 @@ packages: '@vue/shared': 3.2.30 dev: true + /@vue/compiler-dom/3.2.31: + resolution: {integrity: sha512-60zIlFfzIDf3u91cqfqy9KhCKIJgPeqxgveH2L+87RcGU/alT6BRrk5JtUso0OibH3O7NXuNOQ0cDc9beT0wrg==} + dependencies: + '@vue/compiler-core': 3.2.31 + '@vue/shared': 3.2.31 + dev: false + /@vue/compiler-sfc/3.2.26: resolution: {integrity: sha512-ePpnfktV90UcLdsDQUh2JdiTuhV0Skv2iYXxfNMOK/F3Q+2BO0AulcVcfoksOpTJGmhhfosWfMyEaEf0UaWpIw==} dependencies: @@ -2736,6 +2767,21 @@ packages: source-map: 0.6.1 dev: true + /@vue/compiler-sfc/3.2.31: + resolution: {integrity: sha512-748adc9msSPGzXgibHiO6T7RWgfnDcVQD+VVwYgSsyyY8Ans64tALHZANrKtOzvkwznV/F4H7OAod/jIlp/dkQ==} + dependencies: + '@babel/parser': 7.17.0 + '@vue/compiler-core': 3.2.31 + '@vue/compiler-dom': 3.2.31 + '@vue/compiler-ssr': 3.2.31 + '@vue/reactivity-transform': 3.2.31 + '@vue/shared': 3.2.31 + estree-walker: 2.0.2 + magic-string: 0.25.7 + postcss: 8.4.6 + source-map: 0.6.1 + dev: false + /@vue/compiler-ssr/3.2.26: resolution: {integrity: sha512-2mywLX0ODc4Zn8qBoA2PDCsLEZfpUGZcyoFRLSOjyGGK6wDy2/5kyDOWtf0S0UvtoyVq95OTSGIALjZ4k2q/ag==} dependencies: @@ -2756,6 +2802,13 @@ packages: '@vue/shared': 3.2.30 dev: true + /@vue/compiler-ssr/3.2.31: + resolution: {integrity: sha512-mjN0rqig+A8TVDnsGPYJM5dpbjlXeHUm2oZHZwGyMYiGT/F4fhJf/cXy8QpjnLQK4Y9Et4GWzHn9PS8AHUnSkw==} + dependencies: + '@vue/compiler-dom': 3.2.31 + '@vue/shared': 3.2.31 + dev: false + /@vue/devtools-api/6.0.0-beta.21.1: resolution: {integrity: sha512-FqC4s3pm35qGVeXRGOjTsRzlkJjrBLriDS9YXbflHLsfA9FrcKzIyWnLXoNm+/7930E8rRakXuAc2QkC50swAw==} dev: false @@ -2789,6 +2842,16 @@ packages: magic-string: 0.25.7 dev: true + /@vue/reactivity-transform/3.2.31: + resolution: {integrity: sha512-uS4l4z/W7wXdI+Va5pgVxBJ345wyGFKvpPYtdSgvfJfX/x2Ymm6ophQlXXB6acqGHtXuBqNyyO3zVp9b1r0MOA==} + dependencies: + '@babel/parser': 7.17.0 + '@vue/compiler-core': 3.2.31 + '@vue/shared': 3.2.31 + estree-walker: 2.0.2 + magic-string: 0.25.7 + dev: false + /@vue/reactivity/3.2.26: resolution: {integrity: sha512-h38bxCZLW6oFJVDlCcAiUKFnXI8xP8d+eO0pcDxx+7dQfSPje2AO6M9S9QO6MrxQB7fGP0DH0dYQ8ksf6hrXKQ==} dependencies: @@ -2806,6 +2869,12 @@ packages: '@vue/shared': 3.2.30 dev: true + /@vue/reactivity/3.2.31: + resolution: {integrity: sha512-HVr0l211gbhpEKYr2hYe7hRsV91uIVGFYNHj73njbARVGHQvIojkImKMaZNDdoDZOIkMsBc9a1sMqR+WZwfSCw==} + dependencies: + '@vue/shared': 3.2.31 + dev: false + /@vue/runtime-core/3.2.26: resolution: {integrity: sha512-BcYi7qZ9Nn+CJDJrHQ6Zsmxei2hDW0L6AB4vPvUQGBm2fZyC0GXd/4nVbyA2ubmuhctD5RbYY8L+5GUJszv9mQ==} dependencies: @@ -2826,6 +2895,13 @@ packages: '@vue/shared': 3.2.30 dev: true + /@vue/runtime-core/3.2.31: + resolution: {integrity: sha512-Kcog5XmSY7VHFEMuk4+Gap8gUssYMZ2+w+cmGI6OpZWYOEIcbE0TPzzPHi+8XTzAgx1w/ZxDFcXhZeXN5eKWsA==} + dependencies: + '@vue/reactivity': 3.2.31 + '@vue/shared': 3.2.31 + dev: false + /@vue/runtime-dom/3.2.26: resolution: {integrity: sha512-dY56UIiZI+gjc4e8JQBwAifljyexfVCkIAu/WX8snh8vSOt/gMSEGwPRcl2UpYpBYeyExV8WCbgvwWRNt9cHhQ==} dependencies: @@ -2849,6 +2925,14 @@ packages: csstype: 2.6.19 dev: true + /@vue/runtime-dom/3.2.31: + resolution: {integrity: sha512-N+o0sICVLScUjfLG7u9u5XCjvmsexAiPt17GNnaWHJUfsKed5e85/A3SWgKxzlxx2SW/Hw7RQxzxbXez9PtY3g==} + dependencies: + '@vue/runtime-core': 3.2.31 + '@vue/shared': 3.2.31 + csstype: 2.6.19 + dev: false + /@vue/server-renderer/3.2.26_vue@3.2.26: resolution: {integrity: sha512-Jp5SggDUvvUYSBIvYEhy76t4nr1vapY/FIFloWmQzn7UxqaHrrBpbxrqPcTrSgGrcaglj0VBp22BKJNre4aA1w==} peerDependencies: @@ -2878,6 +2962,16 @@ packages: vue: 3.2.30 dev: true + /@vue/server-renderer/3.2.31_vue@3.2.31: + resolution: {integrity: sha512-8CN3Zj2HyR2LQQBHZ61HexF5NReqngLT3oahyiVRfSSvak+oAvVmu8iNLSu6XR77Ili2AOpnAt1y8ywjjqtmkg==} + peerDependencies: + vue: 3.2.31 + dependencies: + '@vue/compiler-ssr': 3.2.31 + '@vue/shared': 3.2.31 + vue: 3.2.31 + dev: false + /@vue/shared/3.2.26: resolution: {integrity: sha512-vPV6Cq+NIWbH5pZu+V+2QHE9y1qfuTq49uNWw4f7FDEeZaDU2H2cx5jcUZOAKW7qTrUS4k6qZPbMy1x4N96nbA==} @@ -2889,6 +2983,10 @@ packages: resolution: {integrity: sha512-B3HouBtUxcfu2w2d+VhdLcVBXKYYhXiFMAfQ+hoe8NUhKkPRkWDIqhpuehCZxVQ3S2dN1P1WfKGlxGC+pfmxGg==} dev: true + /@vue/shared/3.2.31: + resolution: {integrity: sha512-ymN2pj6zEjiKJZbrf98UM2pfDd6F2H7ksKw7NDt/ZZ1fh5Ei39X5tABugtT03ZRlWd9imccoK0hE8hpjpU7irQ==} + dev: false + /@wessberg/stringutil/1.0.19: resolution: {integrity: sha512-9AZHVXWlpN8Cn9k5BC/O0Dzb9E9xfEMXzYrNunwvkUTvuK7xgQPVRZpLo+jWCOZ5r8oBa8NIrHuPEu1hzbb6bg==} engines: {node: '>=8.0.0'} @@ -8310,6 +8408,7 @@ packages: /source-map-resolve/0.6.0: resolution: {integrity: sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w==} + deprecated: See https://github.com/lydell/source-map-resolve#deprecated dependencies: atob: 2.1.2 decode-uri-component: 0.2.0 @@ -9201,6 +9300,16 @@ packages: '@vue/shared': 3.2.30 dev: true + /vue/3.2.31: + resolution: {integrity: sha512-odT3W2tcffTiQCy57nOT93INw1auq5lYLLYtWpPYQQYQOOdHiqFct9Xhna6GJ+pJQaF67yZABraH47oywkJgFw==} + dependencies: + '@vue/compiler-dom': 3.2.31 + '@vue/compiler-sfc': 3.2.31 + '@vue/runtime-dom': 3.2.31 + '@vue/server-renderer': 3.2.31_vue@3.2.31 + '@vue/shared': 3.2.31 + dev: false + /vuex/4.0.2_vue@3.2.26: resolution: {integrity: sha512-M6r8uxELjZIK8kTKDGgZTYX/ahzblnzC4isU1tpmEuOIIKmV+TRdc+H4s8ds2NuZ7wpUTdGRzJRtoj+lI+pc0Q==} peerDependencies: From 3311d00aabeaa7ca53fdfbd069b1046805c34fcd Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 18:23:10 +0900 Subject: [PATCH 18/27] fix: rewrite .at(-1) --- .../playground/css-sourcemap/__tests__/serve.spec.ts | 10 ++++++---- .../playground/vue-sourcemap/__tests__/serve.spec.ts | 6 ++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index f8c622ad315652..cd1d4f0e36b326 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -17,8 +17,10 @@ if (!isBuild) { throw new Error('Not found') } - const extractSourcemap = (content: string) => - fromComment(content.trim().split('\n').at(-1)).toObject() + const extractSourcemap = (content: string) => { + const lines = content.trim().split('\n') + return fromComment(lines[lines.length - 1]).toObject() + } const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { expect(map.sources).toStrictEqual(sources) @@ -36,8 +38,8 @@ if (!isBuild) { } ) const css = await res.text() - const lastLine = css.split('\n').at(-1) - expect(lastLine.includes('/*')).toBe(false) // expect no sourcemap + const lines = css.split('\n') + expect(lines[lines.length - 1].includes('/*')).toBe(false) // expect no sourcemap }) test('linked css with import', async () => { diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts index 973bc430610c4a..91c662e9009a2d 100644 --- a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -16,8 +16,10 @@ if (!isBuild) { throw new Error('Not found') } - const extractSourcemap = (content: string) => - fromComment(content.trim().split('\n').at(-1)).toObject() + const extractSourcemap = (content: string) => { + const lines = content.trim().split('\n') + return fromComment(lines[lines.length - 1]).toObject() + } const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { expect(map.sources).toStrictEqual(sources) From add2cd613feb5d964c3ed4d3b7bbd31ff358cdd3 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 18:24:10 +0900 Subject: [PATCH 19/27] fix: linux sourcemap path escape --- packages/vite/src/node/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index cd3a708a516e75..495e9d348bd501 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -583,7 +583,7 @@ function escapeToLinuxLikePath(path: string) { return path.replace(/^([A-Z]):\//, '/windows/$1/') } if (/^\/[^/]/.test(path)) { - return `/linux/${path}` + return `/linux${path}` } return path } From 5607a244a0de7ad0deebe0b3106b9b76ac1323d3 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 18:33:50 +0900 Subject: [PATCH 20/27] test: ignore no test for serve only test file --- packages/playground/css-sourcemap/__tests__/serve.spec.ts | 4 ++++ packages/playground/vue-sourcemap/__tests__/serve.spec.ts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index cd1d4f0e36b326..0f54f12358972d 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -105,4 +105,8 @@ if (!isBuild) { sources: [`${root}/imported.styl`] }) }) +} else { + test('this file only includes test for serve', () => { + expect(true).toBe(true) + }) } diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts index 91c662e9009a2d..757d1492418af5 100644 --- a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -96,4 +96,8 @@ if (!isBuild) { ] }) }) +} else { + test('this file only includes test for serve', () => { + expect(true).toBe(true) + }) } From 4ca19b0df7c4a0a12114f87fc45aff110f47eee0 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 19:14:08 +0900 Subject: [PATCH 21/27] test: change toMatchSnapshot to toMatchInlineSnapshot --- .../__snapshots__/serve.spec.ts.snap | 92 ------- .../css-sourcemap/__tests__/serve.spec.ts | 152 +++++++++-- .../__snapshots__/serve.spec.ts.snap | 175 ------------ .../vue-sourcemap/__tests__/serve.spec.ts | 248 +++++++++++++++--- 4 files changed, 341 insertions(+), 326 deletions(-) delete mode 100644 packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap delete mode 100644 packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap diff --git a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap deleted file mode 100644 index 60bb675fb43ace..00000000000000 --- a/packages/playground/css-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ /dev/null @@ -1,92 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`imported css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; - -exports[`imported css with import: sourcesContent 1`] = ` -Array [ - ".be-imported { - color: red; -} -", - "@import '@/be-imported.css'; - -.imported-with-import { - color: red; -} -", -] -`; - -exports[`imported css: mappings 1`] = `"AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACb,CAAC;"`; - -exports[`imported css: sourcesContent 1`] = ` -Array [ - ".imported { - color: red; -} -", -] -`; - -exports[`imported less: mappings 1`] = `"AACE;EACE"`; - -exports[`imported less: sourcesContent 1`] = ` -Array [ - ".imported { - &-less { - color: @color; - } -} -", -] -`; - -exports[`imported sass module: mappings 1`] = `"AACE;EACE"`; - -exports[`imported sass module: sourcesContent 1`] = ` -Array [ - ".imported - &-sass-module - color: red -", -] -`; - -exports[`imported sass: mappings 1`] = `"AACE;EACE"`; - -exports[`imported sass: sourcesContent 1`] = ` -Array [ - ".imported - &-sass - color: red -", -] -`; - -exports[`imported stylus: mappings 1`] = `"AACE;EACE,WAAM"`; - -exports[`imported stylus: sourcesContent 1`] = ` -Array [ - ".imported - &-stylus - color red -", -] -`; - -exports[`linked css with import: mappings 1`] = `"AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ"`; - -exports[`linked css with import: sourcesContent 1`] = ` -Array [ - ".be-imported { - color: red; -} -", - "@import '@/be-imported.css'; - -.linked-with-import { - color: red; -} -", -] -`; diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 0f54f12358972d..1e2abf45f26fb8 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -22,10 +22,12 @@ if (!isBuild) { return fromComment(lines[lines.length - 1]).toObject() } - const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { - expect(map.sources).toStrictEqual(sources) - expect(map.mappings).toMatchSnapshot('mappings') - expect(map.sourcesContent).toMatchSnapshot('sourcesContent') + const formatSourcemapForSnapshot = (map: any) => { + const m = { ...map } + delete m.file + delete m.names + m.sources = m.sources.map((source) => source.replace(root, '/root')) + return m } test('linked css', async () => { @@ -53,57 +55,157 @@ if (!isBuild) { ) const css = await res.text() const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/be-imported.css`, `${root}/linked-with-import.css`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/be-imported.css", + "/root/linked-with-import.css", + ], + "sourcesContent": Array [ + ".be-imported { + color: red; + } + ", + "@import '@/be-imported.css'; + + .linked-with-import { + color: red; + } + ", + ], + "version": 3, + } + `) }) test('imported css', async () => { const css = await getStyleTagContentIncluding('.imported ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/imported.css`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACX,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACb,CAAC;", + "sources": Array [ + "/root/imported.css", + ], + "sourcesContent": Array [ + ".imported { + color: red; + } + ", + ], + "version": 3, + } + `) }) test('imported css with import', async () => { const css = await getStyleTagContentIncluding('.imported-with-import ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/be-imported.css`, `${root}/imported-with-import.css`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA;EACE,UAAU;AACZ;;ACAA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/be-imported.css", + "/root/imported-with-import.css", + ], + "sourcesContent": Array [ + ".be-imported { + color: red; + } + ", + "@import '@/be-imported.css'; + + .imported-with-import { + color: red; + } + ", + ], + "version": 3, + } + `) }) test('imported sass', async () => { const css = await getStyleTagContentIncluding('.imported-sass ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/imported.sass`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AACE;EACE", + "sources": Array [ + "/root/imported.sass", + ], + "sourcesContent": Array [ + ".imported + &-sass + color: red + ", + ], + "version": 3, + } + `) }) test('imported sass module', async () => { const css = await getStyleTagContentIncluding('._imported-sass-module_') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/imported.module.sass`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AACE;EACE", + "sources": Array [ + "/root/imported.module.sass", + ], + "sourcesContent": Array [ + ".imported + &-sass-module + color: red + ", + ], + "version": 3, + } + `) }) test('imported less', async () => { const css = await getStyleTagContentIncluding('.imported-less ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/imported.less`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AACE;EACE", + "sources": Array [ + "/root/imported.less", + ], + "sourcesContent": Array [ + ".imported { + &-less { + color: @color; + } + } + ", + ], + "version": 3, + } + `) }) test('imported stylus', async () => { const css = await getStyleTagContentIncluding('.imported-stylus ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/imported.styl`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AACE;EACE,WAAM", + "sources": Array [ + "/root/imported.styl", + ], + "sourcesContent": Array [ + ".imported + &-stylus + color red + ", + ], + "version": 3, + } + `) }) } else { test('this file only includes test for serve', () => { diff --git a/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap b/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap deleted file mode 100644 index a11f3642190d4d..00000000000000 --- a/packages/playground/vue-sourcemap/__tests__/__snapshots__/serve.spec.ts.snap +++ /dev/null @@ -1,175 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`css module: mappings 1`] = `";AAaA;EACE,UAAU;AACZ"`; - -exports[`css module: sourcesContent 1`] = ` -Array [ - " - - - - - - -", -] -`; - -exports[`css scoped: mappings 1`] = `";AAmBA;EACE,UAAU;AACZ"`; - -exports[`css scoped: sourcesContent 1`] = ` -Array [ - " - - - - - - -", -] -`; - -exports[`css: mappings 1`] = `";AAOA;EACE,UAAU;AACZ"`; - -exports[`css: sourcesContent 1`] = ` -Array [ - " - - - - - - -", -] -`; - -exports[`less with additionalData: mappings 1`] = `"AAKA;EACE"`; - -exports[`less with additionalData: sourcesContent 1`] = ` -Array [ - " - - -", -] -`; - -exports[`sass with import: mappings 1`] = `"AAAA;EACE;;ACOF;EACE"`; - -exports[`sass with import: sourcesContent 1`] = ` -Array [ - ".sass-with-import-imported - color: red -", - " - - -", -] -`; - -exports[`sass: mappings 1`] = `"AAKA;EACE"`; - -exports[`sass: sourcesContent 1`] = ` -Array [ - " - - -", -] -`; - -exports[`src imported sass: mappings 1`] = `"AAAA;EACE;;ACCF;EACE"`; - -exports[`src imported sass: sourcesContent 1`] = ` -Array [ - ".src-import-sass-imported - color: red -", - "@import './src-import-imported' - -.src-import-sass - color: red -", -] -`; - -exports[`src imported: mappings 1`] = `"AAAA;EACE,UAAU;AACZ"`; - -exports[`src imported: sourcesContent 1`] = ` -Array [ - ".src-import { - color: red; -} -", -] -`; diff --git a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts index 757d1492418af5..193b0afb9ba73f 100644 --- a/packages/playground/vue-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/vue-sourcemap/__tests__/serve.spec.ts @@ -21,80 +21,260 @@ if (!isBuild) { return fromComment(lines[lines.length - 1]).toObject() } - const assertSourcemap = (map: any, { sources }: { sources: string[] }) => { - expect(map.sources).toStrictEqual(sources) - expect(map.mappings).toMatchSnapshot('mappings') - expect(map.sourcesContent).toMatchSnapshot('sourcesContent') + const formatSourcemapForSnapshot = (map: any) => { + const m = { ...map } + delete m.file + delete m.names + m.sources = m.sources.map((source) => source.replace(root, '/root')) + return m } test('css', async () => { const css = await getStyleTagContentIncluding('.css ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/Css.vue`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": ";AAOA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/Css.vue", + ], + "sourcesContent": Array [ + " + + + + + + + ", + ], + "version": 3, + } + `) }) test('css module', async () => { const css = await getStyleTagContentIncluding('._css-module_') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/Css.vue`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": ";AAaA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/Css.vue", + ], + "sourcesContent": Array [ + " + + + + + + + ", + ], + "version": 3, + } + `) }) test('css scoped', async () => { const css = await getStyleTagContentIncluding('.css-scoped[data-v-') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/Css.vue`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": ";AAmBA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/Css.vue", + ], + "sourcesContent": Array [ + " + + + + + + + ", + ], + "version": 3, + } + `) }) test('sass', async () => { const css = await getStyleTagContentIncluding('.sass ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/Sass.vue`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAKA;EACE", + "sources": Array [ + "/root/Sass.vue", + ], + "sourcesContent": Array [ + " + + + ", + ], + "version": 3, + } + `) }) test('sass with import', async () => { const css = await getStyleTagContentIncluding('.sass-with-import ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [ - `${root}/sassWithImportImported.sass`, - `${root}/SassWithImport.vue` - ] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA;EACE;;ACOF;EACE", + "sources": Array [ + "/root/sassWithImportImported.sass", + "/root/SassWithImport.vue", + ], + "sourcesContent": Array [ + ".sass-with-import-imported + color: red + ", + " + + + ", + ], + "version": 3, + } + `) }) test('less with additionalData', async () => { const css = await getStyleTagContentIncluding('.less ') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/Less.vue`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAKA;EACE", + "sources": Array [ + "/root/Less.vue", + ], + "sourcesContent": Array [ + " + + + ", + ], + "version": 3, + } + `) }) test('src imported', async () => { const css = await getStyleTagContentIncluding('.src-import[data-v-') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [`${root}/src-import/src-import.css`] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA;EACE,UAAU;AACZ", + "sources": Array [ + "/root/src-import/src-import.css", + ], + "sourcesContent": Array [ + ".src-import { + color: red; + } + ", + ], + "version": 3, + } + `) }) test('src imported sass', async () => { const css = await getStyleTagContentIncluding('.src-import-sass[data-v-') const map = extractSourcemap(css) - assertSourcemap(map, { - sources: [ - `${root}/src-import/src-import-imported.sass`, - `${root}/src-import/src-import.sass` - ] - }) + expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` + Object { + "mappings": "AAAA;EACE;;ACCF;EACE", + "sources": Array [ + "/root/src-import/src-import-imported.sass", + "/root/src-import/src-import.sass", + ], + "sourcesContent": Array [ + ".src-import-sass-imported + color: red + ", + "@import './src-import-imported' + + .src-import-sass + color: red + ", + ], + "version": 3, + } + `) }) } else { test('this file only includes test for serve', () => { From 0f563190589e9ffbb104bfb0eb42b6068ed035b3 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 20:13:39 +0900 Subject: [PATCH 22/27] fix: sourcemap warning with plain css --- packages/vite/src/node/plugins/css.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 8c93cb1f41f688..8b206f370336a2 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -621,7 +621,7 @@ async function compileCSS( !needInlineImport && !hasUrl ) { - return { code } + return { code, map: null } } let preprocessorMap: ExistingRawSourceMap | undefined From 7e52db0ab32ad106652cdbb89d81f9889a958e5d Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 6 Mar 2022 20:19:44 +0900 Subject: [PATCH 23/27] test: add sourcemap warning test refs #4939 --- .../css-sourcemap/__tests__/build.spec.ts | 13 +++++++++++++ packages/playground/css-sourcemap/vite.config.js | 3 +++ .../vue-sourcemap/__tests__/build.spec.ts | 13 +++++++++++++ packages/playground/vue-sourcemap/vite.config.js | 5 ++++- scripts/jestPerTestSetup.ts | 10 ++++++++++ 5 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 packages/playground/css-sourcemap/__tests__/build.spec.ts create mode 100644 packages/playground/vue-sourcemap/__tests__/build.spec.ts diff --git a/packages/playground/css-sourcemap/__tests__/build.spec.ts b/packages/playground/css-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..e36c1f52d2c1f8 --- /dev/null +++ b/packages/playground/css-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,13 @@ +import { isBuild } from 'testUtils' + +if (isBuild) { + test('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) + }) +} else { + test('this file only includes test for build', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/css-sourcemap/vite.config.js b/packages/playground/css-sourcemap/vite.config.js index 764aaaa100f773..733e226492fcb0 100644 --- a/packages/playground/css-sourcemap/vite.config.js +++ b/packages/playground/css-sourcemap/vite.config.js @@ -13,5 +13,8 @@ module.exports = { additionalData: '@color: red;' } } + }, + build: { + sourcemap: true } } diff --git a/packages/playground/vue-sourcemap/__tests__/build.spec.ts b/packages/playground/vue-sourcemap/__tests__/build.spec.ts new file mode 100644 index 00000000000000..e36c1f52d2c1f8 --- /dev/null +++ b/packages/playground/vue-sourcemap/__tests__/build.spec.ts @@ -0,0 +1,13 @@ +import { isBuild } from 'testUtils' + +if (isBuild) { + test('should not output sourcemap warning (#4939)', () => { + serverLogs.forEach((log) => { + expect(log).not.toMatch('Sourcemap is likely to be incorrect') + }) + }) +} else { + test('this file only includes test for build', () => { + expect(true).toBe(true) + }) +} diff --git a/packages/playground/vue-sourcemap/vite.config.js b/packages/playground/vue-sourcemap/vite.config.js index 0347aa84a43a1c..045410259fe590 100644 --- a/packages/playground/vue-sourcemap/vite.config.js +++ b/packages/playground/vue-sourcemap/vite.config.js @@ -11,5 +11,8 @@ module.exports = { } } }, - plugins: [vuePlugin()] + plugins: [vuePlugin()], + build: { + sourcemap: true + } } diff --git a/scripts/jestPerTestSetup.ts b/scripts/jestPerTestSetup.ts index 9c15edf9f059bf..312d254a3b11d2 100644 --- a/scripts/jestPerTestSetup.ts +++ b/scripts/jestPerTestSetup.ts @@ -114,6 +114,8 @@ beforeAll(async () => { customLogger: createInMemoryLogger(serverLogs) } + setupConsoleWarnCollector(serverLogs) + global.serverLogs = serverLogs if (!isBuildTest) { @@ -263,3 +265,11 @@ function createInMemoryLogger(logs: string[]): Logger { return logger } + +function setupConsoleWarnCollector(logs: string[]) { + const warn = console.warn + console.warn = (...args) => { + serverLogs.push(args.join(' ')) + return warn.call(console, ...args) + } +} From 59dff9e1558f1fadf6f0ef5fcc192e6b09c46617 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sun, 13 Mar 2022 02:04:12 +0900 Subject: [PATCH 24/27] refactor: use type assertions if it is legal --- packages/plugin-vue/src/style.ts | 11 +++++++++-- packages/vite/src/node/plugins/css.ts | 20 ++++++++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/plugin-vue/src/style.ts b/packages/plugin-vue/src/style.ts index 6f08b6cb40edf3..056ed177f41c56 100644 --- a/packages/plugin-vue/src/style.ts +++ b/packages/plugin-vue/src/style.ts @@ -1,5 +1,5 @@ import type { SFCDescriptor } from 'vue/compiler-sfc' -import type { TransformPluginContext } from 'rollup' +import type { ExistingRawSourceMap, TransformPluginContext } from 'rollup' import type { ResolvedOptions } from '.' import { formatPostcssSourceMap } from 'vite' @@ -45,8 +45,15 @@ export async function transformStyle( return null } + // version property of result.map is declared as string + // but actually it is a number + type RawSourceMap = Omit, 'version'> + const map = result.map - ? formatPostcssSourceMap({ ...result.map, version: 3 }, filename) + ? formatPostcssSourceMap( + result.map as RawSourceMap as ExistingRawSourceMap, + filename + ) : ({ mappings: '' } as any) return { diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 7cb5b7ab633c41..658ecc76ebbffc 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -47,6 +47,7 @@ import type { ModuleNode } from '../server/moduleGraph' import { transform, formatMessages } from 'esbuild' import { addToHTMLProxyTransformResult } from './html' import { injectSourcesContent, getCodeWithSourcemap } from '../server/sourcemap' +import type { RawSourceMap } from '@ampproject/remapping' // const debug = createDebugger('vite:css') @@ -806,8 +807,17 @@ async function compileCSS( } } + const postcssMapBeforeFormat = postcssResult.map.toJSON() + + // version property of postcssMapBeforeFormat is declared as string + // but actually it is a number + type RawSourceMap = Omit< + Exclude, + 'version' + > + const postcssMap = formatPostcssSourceMap( - { ...postcssResult.map.toJSON(), version: 3 }, + postcssMapBeforeFormat as RawSourceMap as ExistingRawSourceMap, cleanUrl(id) ) @@ -838,7 +848,7 @@ export function formatPostcssSourceMap( mappings: rawMap.mappings, names: rawMap.names, sources, - version: +rawMap.version + version: rawMap.version } } @@ -849,8 +859,10 @@ function combineSourcemapsIfExists( ): ExistingRawSourceMap | undefined { return map1 && map2 ? (combineSourcemaps(filename, [ - { ...map1, version: 3 }, - { ...map2, version: 3 } + // type of version property of ExistingRawSourceMap is number + // but it is always 3 + map1 as RawSourceMap, + map2 as RawSourceMap ]) as ExistingRawSourceMap) : map1 } From 5b0d47b1a81cb5b745abd18b6952c0fcf4071ed7 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Mon, 14 Mar 2022 02:34:22 +0900 Subject: [PATCH 25/27] refactor: rewrite RawSourceMap type --- packages/plugin-vue/src/style.ts | 9 ++++----- packages/vite/package.json | 1 + packages/vite/src/node/plugins/css.ts | 13 ++++--------- pnpm-lock.yaml | 17 ++++++++++++++++- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/packages/plugin-vue/src/style.ts b/packages/plugin-vue/src/style.ts index 056ed177f41c56..c124f3ec744e4f 100644 --- a/packages/plugin-vue/src/style.ts +++ b/packages/plugin-vue/src/style.ts @@ -1,6 +1,7 @@ import type { SFCDescriptor } from 'vue/compiler-sfc' import type { ExistingRawSourceMap, TransformPluginContext } from 'rollup' import type { ResolvedOptions } from '.' +import type { RawSourceMap } from 'source-map' import { formatPostcssSourceMap } from 'vite' // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types @@ -45,13 +46,11 @@ export async function transformStyle( return null } - // version property of result.map is declared as string - // but actually it is a number - type RawSourceMap = Omit, 'version'> - const map = result.map ? formatPostcssSourceMap( - result.map as RawSourceMap as ExistingRawSourceMap, + // version property of result.map is declared as string + // but actually it is a number + result.map as Omit as ExistingRawSourceMap, filename ) : ({ mappings: '' } as any) diff --git a/packages/vite/package.json b/packages/vite/package.json index 7b6f8357a84bce..f9d77052c7fcab 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -109,6 +109,7 @@ "resolve.exports": "^1.1.0", "rollup-plugin-license": "^2.6.1", "sirv": "^2.0.2", + "source-map-js": "^1.0.2", "source-map-support": "^0.5.21", "strip-ansi": "^6.0.1", "terser": "^5.10.0", diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 658ecc76ebbffc..856b059263586e 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -807,17 +807,12 @@ async function compileCSS( } } - const postcssMapBeforeFormat = postcssResult.map.toJSON() - - // version property of postcssMapBeforeFormat is declared as string - // but actually it is a number - type RawSourceMap = Omit< - Exclude, - 'version' - > + const rawPostcssMap = postcssResult.map.toJSON() const postcssMap = formatPostcssSourceMap( - postcssMapBeforeFormat as RawSourceMap as ExistingRawSourceMap, + // version property of rawPostcssMap is declared as string + // but actually it is a number + rawPostcssMap as Omit as ExistingRawSourceMap, cleanUrl(id) ) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8aabd2199b95b4..5d42271e7ee16d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -851,6 +851,7 @@ importers: rollup: ^2.59.0 rollup-plugin-license: ^2.6.1 sirv: ^2.0.2 + source-map-js: ^1.0.2 source-map-support: ^0.5.21 strip-ansi: ^6.0.1 terser: ^5.10.0 @@ -923,6 +924,7 @@ importers: resolve.exports: 1.1.0 rollup-plugin-license: 2.6.1_rollup@2.62.0 sirv: 2.0.2 + source-map-js: 1.0.2 source-map-support: 0.5.21 strip-ansi: 6.0.1 terser: 5.10.0_acorn@8.7.0 @@ -5046,6 +5048,19 @@ packages: peerDependenciesMeta: debug: optional: true + dev: false + + /follow-redirects/1.14.6_debug@4.3.3: + resolution: {integrity: sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + dependencies: + debug: 4.3.3 + dev: true /form-data/3.0.1: resolution: {integrity: sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==} @@ -5435,7 +5450,7 @@ packages: engines: {node: '>=8.0.0'} dependencies: eventemitter3: 4.0.7 - follow-redirects: 1.14.6 + follow-redirects: 1.14.6_debug@4.3.3 requires-port: 1.0.0 transitivePeerDependencies: - debug From 8e479d338c1b4b68ef69772127a136e6824ce4ae Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Mon, 14 Mar 2022 02:37:24 +0900 Subject: [PATCH 26/27] refactor: remove unused imports --- packages/vite/src/node/__tests__/plugins/css.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index f25926437fb83f..539ec2f1af1810 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -2,7 +2,6 @@ import { cssUrlRE, cssPlugin } from '../../plugins/css' import { resolveConfig } from '../../config' import fs from 'fs' import path from 'path' -import { normalizePath } from '../../utils' describe('search css url function', () => { test('some spaces before it', () => { From a1e03f767013ed32b24462ea31c6b1018d43e361 Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Mon, 14 Mar 2022 03:49:42 +0900 Subject: [PATCH 27/27] feat: return sourcemap with additionalData --- .../css-sourcemap/__tests__/serve.spec.ts | 4 +-- .../playground/css-sourcemap/imported.styl | 2 +- .../playground/css-sourcemap/package.json | 1 + .../playground/css-sourcemap/vite.config.js | 20 +++++++++++ packages/vite/src/node/plugins/css.ts | 34 +++++++++++-------- pnpm-lock.yaml | 3 ++ 6 files changed, 46 insertions(+), 18 deletions(-) diff --git a/packages/playground/css-sourcemap/__tests__/serve.spec.ts b/packages/playground/css-sourcemap/__tests__/serve.spec.ts index 1e2abf45f26fb8..50c256298143ab 100644 --- a/packages/playground/css-sourcemap/__tests__/serve.spec.ts +++ b/packages/playground/css-sourcemap/__tests__/serve.spec.ts @@ -193,14 +193,14 @@ if (!isBuild) { const map = extractSourcemap(css) expect(formatSourcemapForSnapshot(map)).toMatchInlineSnapshot(` Object { - "mappings": "AACE;EACE,WAAM", + "mappings": "AACE;EACE,cAAM", "sources": Array [ "/root/imported.styl", ], "sourcesContent": Array [ ".imported &-stylus - color red + color blue-red-mixed ", ], "version": 3, diff --git a/packages/playground/css-sourcemap/imported.styl b/packages/playground/css-sourcemap/imported.styl index ad3a5e4bf8141f..83c7cf517acf4d 100644 --- a/packages/playground/css-sourcemap/imported.styl +++ b/packages/playground/css-sourcemap/imported.styl @@ -1,3 +1,3 @@ .imported &-stylus - color red + color blue-red-mixed diff --git a/packages/playground/css-sourcemap/package.json b/packages/playground/css-sourcemap/package.json index 2d71c4fcc29cfc..c29f18d4dee0d7 100644 --- a/packages/playground/css-sourcemap/package.json +++ b/packages/playground/css-sourcemap/package.json @@ -11,6 +11,7 @@ "devDependencies": { "convert-source-map": "^1.8.0", "less": "^4.1.2", + "magic-string": "^0.25.7", "sass": "^1.43.4", "stylus": "^0.55.0" } diff --git a/packages/playground/css-sourcemap/vite.config.js b/packages/playground/css-sourcemap/vite.config.js index 733e226492fcb0..2e70a4a0894406 100644 --- a/packages/playground/css-sourcemap/vite.config.js +++ b/packages/playground/css-sourcemap/vite.config.js @@ -1,3 +1,5 @@ +const MagicString = require('magic-string') + /** * @type {import('vite').UserConfig} */ @@ -11,6 +13,24 @@ module.exports = { preprocessorOptions: { less: { additionalData: '@color: red;' + }, + styl: { + additionalData: (content, filename) => { + const ms = new MagicString(content, { filename }) + + const willBeReplaced = 'blue-red-mixed' + const start = content.indexOf(willBeReplaced) + ms.overwrite(start, start + willBeReplaced.length, 'purple') + + const map = ms.generateMap({ hires: true }) + map.file = filename + map.sources = [filename] + + return { + content: ms.toString(), + map + } + } } } }, diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 856b059263586e..db8e0a2679f74f 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -1060,9 +1060,18 @@ AtImportHoistPlugin.postcss = true // Preprocessor support. This logic is largely replicated from @vue/compiler-sfc +type PreprocessorAdditionalDataResult = + | string + | { content: string; map?: ExistingRawSourceMap } + type PreprocessorAdditionalData = | string - | ((source: string, filename: string) => string | Promise) + | (( + source: string, + filename: string + ) => + | PreprocessorAdditionalDataResult + | Promise) type StylePreprocessorOptions = { [key: string]: any @@ -1457,32 +1466,27 @@ async function getSource( sep: string = '' ): Promise<{ content: string; map?: ExistingRawSourceMap }> { if (!additionalData) return { content: source } + if (typeof additionalData === 'function') { const newContent = await additionalData(source, filename) - const ms = new MagicString(source) - ms.overwrite(0, source.length, newContent) - - return { - content: ms.toString(), - map: generateWithAbsoluteFilenameMap(ms, filename) + if (typeof newContent === 'string') { + return { content: newContent } } + return newContent } const ms = new MagicString(source) ms.appendLeft(0, sep) ms.appendLeft(0, additionalData) - return { - content: ms.toString(), - map: generateWithAbsoluteFilenameMap(ms, filename) - } -} - -function generateWithAbsoluteFilenameMap(ms: MagicString, filename: string) { const map = ms.generateMap({ hires: true }) map.file = filename map.sources = [filename] - return map + + return { + content: ms.toString(), + map + } } const preProcessors = Object.freeze({ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5d42271e7ee16d..8f255ac07069ce 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -154,11 +154,13 @@ importers: specifiers: convert-source-map: ^1.8.0 less: ^4.1.2 + magic-string: ^0.25.7 sass: ^1.43.4 stylus: ^0.55.0 devDependencies: convert-source-map: 1.8.0 less: 4.1.2 + magic-string: 0.25.7 sass: 1.45.1 stylus: 0.55.0 @@ -6825,6 +6827,7 @@ packages: resolution: {integrity: sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==} engines: {node: '>=4'} hasBin: true + requiresBuild: true dev: true /mime/2.6.0: