diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 76faba2173450c..61318a58cf3279 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -45,6 +45,7 @@ import { emptyCssComments, generateCodeFrame, getHash, + getPackageManagerCommand, isDataUrl, isExternalUrl, isObject, @@ -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( diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 9ddc8c3a1f7791..82e83d9a95989b 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -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}`) + } +}