Skip to content

Commit

Permalink
feat(css): format error (#9909)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Aug 30, 2022
1 parent c9521e7 commit 632fedf
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 60 deletions.
20 changes: 20 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getPotentialTsSrcPaths,
injectQuery,
isWindows,
posToNumber,
resolveHostname
} from '../utils'

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

describe('posToNumber', () => {
test('simple', () => {
const actual = posToNumber('a\nb', { line: 2, column: 0 })
expect(actual).toBe(2)
})
test('pass though pos', () => {
const actual = posToNumber('a\nb', 2)
expect(actual).toBe(2)
})
test('empty line', () => {
const actual = posToNumber('a\n\nb', { line: 3, column: 0 })
expect(actual).toBe(3)
})
test('out of range', () => {
const actual = posToNumber('a\nb', { line: 4, column: 0 })
expect(actual).toBe(4)
})
})

describe('getHash', () => {
test('8-digit hex', () => {
const hash = getHash(Buffer.alloc(0))
Expand Down
125 changes: 69 additions & 56 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -804,8 +804,8 @@ async function compileCSS(
atImportResolvers
)

if (preprocessResult.errors.length) {
throw preprocessResult.errors[0]
if (preprocessResult.error) {
throw preprocessResult.error
}

code = preprocessResult.code
Expand Down Expand Up @@ -894,55 +894,66 @@ async function compileCSS(
}
}

// postcss is an unbundled dep and should be lazy imported
const postcssResult = await (await import('postcss'))
.default(postcssPlugins)
.process(code, {
...postcssOptions,
to: id,
from: id,
...(devSourcemap
? {
map: {
inline: false,
annotation: false,
// postcss may return virtual files
// we cannot obtain content of them, so this needs to be enabled
sourcesContent: true
// when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
// prev: preprocessorMap,
let postcssResult: PostCSS.Result
try {
// postcss is an unbundled dep and should be lazy imported
postcssResult = await (await import('postcss'))
.default(postcssPlugins)
.process(code, {
...postcssOptions,
to: id,
from: id,
...(devSourcemap
? {
map: {
inline: false,
annotation: false,
// postcss may return virtual files
// we cannot obtain content of them, so this needs to be enabled
sourcesContent: true
// when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
// prev: preprocessorMap,
}
}
}
: {})
})

// record CSS dependencies from @imports
for (const message of postcssResult.messages) {
if (message.type === 'dependency') {
deps.add(normalizePath(message.file as string))
} else if (message.type === 'dir-dependency') {
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
const { dir, glob: globPattern = '**' } = message
const pattern =
glob.escapePath(normalizePath(path.resolve(path.dirname(id), dir))) +
`/` +
globPattern
const files = glob.sync(pattern, {
ignore: ['**/node_modules/**']
: {})
})
for (let i = 0; i < files.length; i++) {
deps.add(files[i])
}
} else if (message.type === 'warning') {
let msg = `[vite:css] ${message.text}`
if (message.line && message.column) {
msg += `\n${generateCodeFrame(code, {
line: message.line,
column: message.column
})}`

// record CSS dependencies from @imports
for (const message of postcssResult.messages) {
if (message.type === 'dependency') {
deps.add(normalizePath(message.file as string))
} else if (message.type === 'dir-dependency') {
// https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies
const { dir, glob: globPattern = '**' } = message
const pattern =
glob.escapePath(normalizePath(path.resolve(path.dirname(id), dir))) +
`/` +
globPattern
const files = glob.sync(pattern, {
ignore: ['**/node_modules/**']
})
for (let i = 0; i < files.length; i++) {
deps.add(files[i])
}
} else if (message.type === 'warning') {
let msg = `[vite:css] ${message.text}`
if (message.line && message.column) {
msg += `\n${generateCodeFrame(code, {
line: message.line,
column: message.column
})}`
}
config.logger.warn(colors.yellow(msg))
}
config.logger.warn(colors.yellow(msg))
}
} catch (e) {
e.message = `[postcss] ${e.message}`
e.code = code
e.loc = {
column: e.column,
line: e.line
}
throw e
}

if (!devSourcemap) {
Expand Down Expand Up @@ -1257,6 +1268,7 @@ async function minifyCSS(css: string, config: ResolvedConfig) {
return code
} catch (e) {
if (e.errors) {
e.message = '[esbuild css minify] ' + e.message
const msgs = await formatMessages(e.errors, { kind: 'error' })
e.frame = '\n' + msgs.join('\n')
e.loc = e.errors[0].location
Expand Down Expand Up @@ -1366,7 +1378,7 @@ export interface StylePreprocessorResults {
code: string
map?: ExistingRawSourceMap | undefined
additionalMap?: ExistingRawSourceMap | undefined
errors: RollupError[]
error?: RollupError
deps: string[]
}

Expand Down Expand Up @@ -1470,14 +1482,14 @@ const scss: SassStylePreprocessor = async (
code: result.css.toString(),
map,
additionalMap,
errors: [],
deps
}
} catch (e) {
// normalize SASS error
e.message = `[sass] ${e.message}`
e.id = e.file
e.frame = e.formatted
return { code: '', errors: [e], deps: [] }
return { code: '', error: e, deps: [] }
}
}

Expand Down Expand Up @@ -1589,13 +1601,15 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => {
} catch (e) {
const error = e as Less.RenderError
// normalize error info
const normalizedError: RollupError = new Error(error.message || error.type)
const normalizedError: RollupError = new Error(
`[less] ${error.message || error.type}`
)
normalizedError.loc = {
file: error.filename || options.filename,
line: error.line,
column: error.column
}
return { code: '', errors: [normalizedError], deps: [] }
return { code: '', error: normalizedError, deps: [] }
}

const map: ExistingRawSourceMap = result.map && JSON.parse(result.map)
Expand All @@ -1607,8 +1621,7 @@ const less: StylePreprocessor = async (source, root, options, resolvers) => {
code: result.css.toString(),
map,
additionalMap,
deps: result.imports,
errors: []
deps: result.imports
}
}

Expand Down Expand Up @@ -1722,11 +1735,11 @@ const styl: StylePreprocessor = async (source, root, options) => {
code: result,
map: formatStylusSourceMap(map, root),
additionalMap,
errors: [],
deps
}
} catch (e) {
return { code: '', errors: [e], deps: [] }
e.message = `[stylus] ${e.message}`
return { code: '', error: e, deps: [] }
}
}

Expand Down
6 changes: 2 additions & 4 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,10 +433,8 @@ export function posToNumber(
const lines = source.split(splitRE)
const { line, column } = pos
let start = 0
for (let i = 0; i < line - 1; i++) {
if (lines[i]) {
start += lines[i].length + 1
}
for (let i = 0; i < line - 1 && i < lines.length; i++) {
start += lines[i].length + 1
}
return start + column
}
Expand Down

0 comments on commit 632fedf

Please sign in to comment.