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 #27 #182

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { isFilePathMatchedByEslintIgnore, isFilePathMatchedByPrettierIgnore } fr

const path = require('path');

const rawResolve = require.resolve;

let outputChannel;

async function formatter(document) {
Expand All @@ -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 "<user_workspace>/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 "<user_workspace>/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;
}
}

Expand Down