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

fix(css): enhance error message for missing preprocessor dependency #11485

Merged
merged 7 commits into from Jul 31, 2023
4 changes: 3 additions & 1 deletion packages/vite/src/node/plugins/css.ts
Expand Up @@ -45,6 +45,7 @@ import {
emptyCssComments,
generateCodeFrame,
getHash,
getPackageManagerCommand,
isDataUrl,
isExternalUrl,
isObject,
Expand Down Expand Up @@ -1694,8 +1695,9 @@ function loadPreprocessor(
return (loadedPreprocessors[lang] = _require(resolved))
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
const installCommand = getPackageManagerCommand('install')
throw new Error(
`Preprocessor dependency "${lang}" not found. Did you install it?`,
`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`,
)
} else {
const message = new Error(
Expand Down
22 changes: 22 additions & 0 deletions packages/vite/src/node/utils.ts
Expand Up @@ -1257,3 +1257,25 @@ const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g
export function escapeRegex(str: string): string {
return str.replace(escapeRegexRE, '\\$&')
}

type CommandType = 'install' | 'uninstall' | 'update'
export function getPackageManagerCommand(
type: CommandType = 'install',
): string {
const packageManager =
process.env.npm_config_user_agent?.split(' ')[0].split('/')[0] || 'npm'
switch (type) {
case 'install':
return packageManager === 'npm' ? 'npm install' : `${packageManager} add`
case 'uninstall':
return packageManager === 'npm'
? 'npm uninstall'
: `${packageManager} remove`
case 'update':
return packageManager === 'yarn'
? 'yarn upgrade'
: `${packageManager} update`
default:
throw new TypeError(`Unknown command type: ${type}`)
}
}