In VS Code, I'm getting this error, 'Failed to load module. Attempted to load prettier from package.json'
This is a solution that worked for me
1. Install Prettier Globally via npm if you have never installed it globally
npm i prettier -g
2. Search & Use the Prettier Path
Extension Settings in your VS Code Settings
// You can navigate to VS Code Settings > Extensions > Prettier
for all Prettier Extension Settings
3. Update the Prettier Path
to your globally installed Prettier.
For Example
/usr/local/lib/node_modules/prettier
(Mac OS)
\AppData\Roaming\npm\node_modules\prettier
(Windows)
Update
It now works for me with prettier-vscode
4.1.1 and prettier
2.0.4, give it a try. I can either use the bundled or locally installed version of prettier.
Notable changes:
- [4.0.0] Updated prettier to 2.0
- [4.1.0] Added configuration option withNodeModules to enable processing of files in the node_modules folder [default: false]
- [4.1.0] Support loading Prettier from node_modules even if it doesn't appear as a direct dependency in a package.json
Original post
I encountered this problem when inspecting the source code of an external package under node_modules
.
A workaround is to remove the prettier
entry in package.json
of this package - no local/global prettier
install necessary. Example:
{
"devDependencies": {
...
"prettier": "^1.19.1", // remove this line completely
},
}
Keep the package.json
valid - no trailing comma, don't just comment the line out. The reason why it works is:
The extension searches the tree down until we file a package.json. If that package.json contains prettier, the extension uses that, otherwise it will fall back to using the bundled version of prettier. Link
My guess is, that the extension wants to use prettier
from the package, even if it is devDependencies
.
There should be no harm to drop the devDependency
from a package in node_modules
. This also makes it possible to use the prettier
version bundled with prettier-vscode
(no install necessary).
When setting up Prettier it is important to configure it per-project. Not every project uses the same code style, thus it is important to respect the style of whatever project you are currently working in.
The demo repo bahmutov/prettier-config-example
has two subfolders, each with its distinct code style, enforced by Prettier. In reality, each of your repos will have its style; I am using subfolders in order to keep the example simple.
npm install --save-dev --save-exact prettier