diff --git a/src/extension.js b/src/extension.js index f67fd9f..4409328 100644 --- a/src/extension.js +++ b/src/extension.js @@ -12,6 +12,8 @@ import { isFilePathMatchedByEslintIgnore, isFilePathMatchedByPrettierIgnore } fr const path = require('path'); +const rawResolve = require.resolve; + let outputChannel; async function formatter(document) { @@ -33,15 +35,44 @@ async function formatter(document) { const text = document.getText(range); const extensionConfig = workspace?.getConfiguration('vs-code-prettier-eslint'); + + /** + * In some case, user cannot format his/her codes and the error + * is "cannot find module XXX". + * + * The reason is easy.This project depends on `prettier-eslint` which + * uses require.resolve API to search a module path, unfortunately, it + * doesn't search a module path under "/node_modules" as + * expected. + * + * To fix this bug, before we call `format`, we rewrite require.resolve, + * and take a try to search module path under "/node_modules" + * firstly.When `format` is finished, restore require.resolve. + */ + + require.resolve = function resolve(...args) { + const [moduleName] = args; + let modulePath = ''; + try { + modulePath = rawResolve(moduleName, { paths: [workspaceDir] }); + } catch (err) { + modulePath = rawResolve(...args); + } + return modulePath; + }; + const formatted = await format({ text, filePath: document.fileName, extensionConfig, }); + return [TextEdit.replace(range, formatted)]; } } catch (err) { outputChannel.appendLine(`Error: ${err.message} \n${err.stack}`); + } finally { + require.resolve = rawResolve; } }