Skip to content

Commit 632fedf

Browse files
authored
feat(css): format error (#9909)
1 parent c9521e7 commit 632fedf

3 files changed

Lines changed: 91 additions & 60 deletions

File tree

packages/vite/src/node/__tests__/utils.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
getPotentialTsSrcPaths,
77
injectQuery,
88
isWindows,
9+
posToNumber,
910
resolveHostname
1011
} from '../utils'
1112

@@ -156,6 +157,25 @@ test('ts import of file with .js and query param', () => {
156157
])
157158
})
158159

160+
describe('posToNumber', () => {
161+
test('simple', () => {
162+
const actual = posToNumber('a\nb', { line: 2, column: 0 })
163+
expect(actual).toBe(2)
164+
})
165+
test('pass though pos', () => {
166+
const actual = posToNumber('a\nb', 2)
167+
expect(actual).toBe(2)
168+
})
169+
test('empty line', () => {
170+
const actual = posToNumber('a\n\nb', { line: 3, column: 0 })
171+
expect(actual).toBe(3)
172+
})
173+
test('out of range', () => {
174+
const actual = posToNumber('a\nb', { line: 4, column: 0 })
175+
expect(actual).toBe(4)
176+
})
177+
})
178+
159179
describe('getHash', () => {
160180
test('8-digit hex', () => {
161181
const hash = getHash(Buffer.alloc(0))

packages/vite/src/node/plugins/css.ts

Lines changed: 69 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -804,8 +804,8 @@ async function compileCSS(
804804
atImportResolvers
805805
)
806806

807-
if (preprocessResult.errors.length) {
808-
throw preprocessResult.errors[0]
807+
if (preprocessResult.error) {
808+
throw preprocessResult.error
809809
}
810810

811811
code = preprocessResult.code
@@ -894,55 +894,66 @@ async function compileCSS(
894894
}
895895
}
896896

897-
// postcss is an unbundled dep and should be lazy imported
898-
const postcssResult = await (await import('postcss'))
899-
.default(postcssPlugins)
900-
.process(code, {
901-
...postcssOptions,
902-
to: id,
903-
from: id,
904-
...(devSourcemap
905-
? {
906-
map: {
907-
inline: false,
908-
annotation: false,
909-
// postcss may return virtual files
910-
// we cannot obtain content of them, so this needs to be enabled
911-
sourcesContent: true
912-
// when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
913-
// prev: preprocessorMap,
897+
let postcssResult: PostCSS.Result
898+
try {
899+
// postcss is an unbundled dep and should be lazy imported
900+
postcssResult = await (await import('postcss'))
901+
.default(postcssPlugins)
902+
.process(code, {
903+
...postcssOptions,
904+
to: id,
905+
from: id,
906+
...(devSourcemap
907+
? {
908+
map: {
909+
inline: false,
910+
annotation: false,
911+
// postcss may return virtual files
912+
// we cannot obtain content of them, so this needs to be enabled
913+
sourcesContent: true
914+
// when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
915+
// prev: preprocessorMap,
916+
}
914917
}
915-
}
916-
: {})
917-
})
918-
919-
// record CSS dependencies from @imports
920-
for (const message of postcssResult.messages) {
921-
if (message.type === 'dependency') {
922-
deps.add(normalizePath(message.file as string))
923-
} else if (message.type === 'dir-dependency') {
924-
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
925-
const { dir, glob: globPattern = '**' } = message
926-
const pattern =
927-
glob.escapePath(normalizePath(path.resolve(path.dirname(id), dir))) +
928-
`/` +
929-
globPattern
930-
const files = glob.sync(pattern, {
931-
ignore: ['**/node_modules/**']
918+
: {})
932919
})
933-
for (let i = 0; i < files.length; i++) {
934-
deps.add(files[i])
935-
}
936-
} else if (message.type === 'warning') {
937-
let msg = `[vite:css] ${message.text}`
938-
if (message.line && message.column) {
939-
msg += `\n${generateCodeFrame(code, {
940-
line: message.line,
941-
column: message.column
942-
})}`
920+
921+
// record CSS dependencies from @imports
922+
for (const message of postcssResult.messages) {
923+
if (message.type === 'dependency') {
924+
deps.add(normalizePath(message.file as string))
925+
} else if (message.type === 'dir-dependency') {
926+
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
927+
const { dir, glob: globPattern = '**' } = message
928+
const pattern =
929+
glob.escapePath(normalizePath(path.resolve(path.dirname(id), dir))) +
930+
`/` +
931+
globPattern
932+
const files = glob.sync(pattern, {
933+
ignore: ['**/node_modules/**']
934+
})
935+
for (let i = 0; i < files.length; i++) {
936+
deps.add(files[i])
937+
}
938+
} else if (message.type === 'warning') {
939+
let msg = `[vite:css] ${message.text}`
940+
if (message.line && message.column) {
941+
msg += `\n${generateCodeFrame(code, {
942+
line: message.line,
943+
column: message.column
944+
})}`
945+
}
946+
config.logger.warn(colors.yellow(msg))
943947
}
944-
config.logger.warn(colors.yellow(msg))
945948
}
949+
} catch (e) {
950+
e.message = `[postcss] ${e.message}`
951+
e.code = code
952+
e.loc = {
953+
column: e.column,
954+
line: e.line
955+
}
956+
throw e
946957
}
947958

948959
if (!devSourcemap) {
@@ -1257,6 +1268,7 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
12571268
return code
12581269
} catch (e) {
12591270
if (e.errors) {
1271+
e.message = '[esbuild css minify] ' + e.message
12601272
const msgs = await formatMessages(e.errors, { kind: 'error' })
12611273
e.frame = '\n' + msgs.join('\n')
12621274
e.loc = e.errors[0].location
@@ -1366,7 +1378,7 @@ export interface StylePreprocessorResults {
13661378
code: string
13671379
map?: ExistingRawSourceMap | undefined
13681380
additionalMap?: ExistingRawSourceMap | undefined
1369-
errors: RollupError[]
1381+
error?: RollupError
13701382
deps: string[]
13711383
}
13721384

@@ -1470,14 +1482,14 @@ const scss: SassStylePreprocessor = async (
14701482
code: result.css.toString(),
14711483
map,
14721484
additionalMap,
1473-
errors: [],
14741485
deps
14751486
}
14761487
} catch (e) {
14771488
// normalize SASS error
1489+
e.message = `[sass] ${e.message}`
14781490
e.id = e.file
14791491
e.frame = e.formatted
1480-
return { code: '', errors: [e], deps: [] }
1492+
return { code: '', error: e, deps: [] }
14811493
}
14821494
}
14831495

@@ -1589,13 +1601,15 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => {
15891601
} catch (e) {
15901602
const error = e as Less.RenderError
15911603
// normalize error info
1592-
const normalizedError: RollupError = new Error(error.message || error.type)
1604+
const normalizedError: RollupError = new Error(
1605+
`[less] ${error.message || error.type}`
1606+
)
15931607
normalizedError.loc = {
15941608
file: error.filename || options.filename,
15951609
line: error.line,
15961610
column: error.column
15971611
}
1598-
return { code: '', errors: [normalizedError], deps: [] }
1612+
return { code: '', error: normalizedError, deps: [] }
15991613
}
16001614

16011615
const map: ExistingRawSourceMap = result.map && JSON.parse(result.map)
@@ -1607,8 +1621,7 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => {
16071621
code: result.css.toString(),
16081622
map,
16091623
additionalMap,
1610-
deps: result.imports,
1611-
errors: []
1624+
deps: result.imports
16121625
}
16131626
}
16141627

@@ -1722,11 +1735,11 @@ const styl: StylePreprocessor = async (source, root, options) => {
17221735
code: result,
17231736
map: formatStylusSourceMap(map, root),
17241737
additionalMap,
1725-
errors: [],
17261738
deps
17271739
}
17281740
} catch (e) {
1729-
return { code: '', errors: [e], deps: [] }
1741+
e.message = `[stylus] ${e.message}`
1742+
return { code: '', error: e, deps: [] }
17301743
}
17311744
}
17321745

packages/vite/src/node/utils.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -433,10 +433,8 @@ export function posToNumber(
433433
const lines = source.split(splitRE)
434434
const { line, column } = pos
435435
let start = 0
436-
for (let i = 0; i < line - 1; i++) {
437-
if (lines[i]) {
438-
start += lines[i].length + 1
439-
}
436+
for (let i = 0; i < line - 1 && i < lines.length; i++) {
437+
start += lines[i].length + 1
440438
}
441439
return start + column
442440
}

0 commit comments

Comments
 (0)