Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(css): format error #9909

Merged
merged 2 commits into from Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Expand Up @@ -6,6 +6,7 @@ import {
getPotentialTsSrcPaths,
injectQuery,
isWindows,
posToNumber,
resolveHostname
} from '../utils'

Expand Down Expand Up @@ -156,6 +157,21 @@ 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)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was returning 2.

})
})

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
Expand Up @@ -803,8 +803,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 @@ -893,55 +893,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 @@ -1256,6 +1267,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 @@ -1365,7 +1377,7 @@ export interface StylePreprocessorResults {
code: string
map?: ExistingRawSourceMap | undefined
additionalMap?: ExistingRawSourceMap | undefined
errors: RollupError[]
error?: RollupError
deps: string[]
}

Expand Down Expand Up @@ -1469,14 +1481,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 @@ -1588,13 +1600,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 @@ -1606,8 +1620,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 @@ -1721,11 +1734,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
2 changes: 2 additions & 0 deletions packages/vite/src/node/utils.ts
Expand Up @@ -436,6 +436,8 @@ export function posToNumber(
for (let i = 0; i < line - 1; i++) {
if (lines[i]) {
start += lines[i].length + 1
} else {
start++
}
}
return start + column
Expand Down