From 65e5c229a362dd8cbb28393f6410e950dacaa04b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Wang=20=E6=B1=AA=E6=9D=B1=E9=99=BD?= Date: Mon, 31 Jul 2023 16:26:38 +0800 Subject: [PATCH] fix(css): enhance error message for missing preprocessor dependency (#11485) --- packages/vite/src/node/plugins/css.ts | 4 +++- packages/vite/src/node/utils.ts | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index bbd380ddb56409..2b8d40b2bb20bd 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 a319fcf9e4f7d3..27a619947c0b0d 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}`) + } +}