Skip to content

Commit 6e4ae76

Browse files
committed
🐛 fix prettier conf in vscode
VSCode's Prettier extension doesn't resolve esm imports correctly, so we have to help it out.
1 parent 3418ff0 commit 6e4ae76

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

packages/code-style/src/prettierrc.mts

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
import { execSync } from 'child_process';
44
import deepmerge from 'deepmerge';
5-
import type { Config } from 'prettier';
5+
import type { Config, Plugin } from 'prettier';
66
import type { RubyConfig } from '@prettier/plugin-ruby';
7-
import * as plugin_ruby from '@prettier/plugin-ruby';
7+
import plugin_ruby from '@prettier/plugin-ruby';
88
import * as plugin_packagejson from 'prettier-plugin-packagejson';
99

10+
// eslint-disable-next-line n/no-process-env -- this is the only config we need.
11+
const in_vscode_ext = process.env.VSCODE_PID != null;
12+
1013
const is_prettier_gem_installed: boolean = (() => {
1114
try {
1215
return (
@@ -20,6 +23,34 @@ const is_prettier_gem_installed: boolean = (() => {
2023
}
2124
})();
2225

26+
function resolve_plugin(
27+
plugin: 'prettier-plugin-packagejson' | '@prettier/plugin-ruby',
28+
): string | Plugin {
29+
if (!in_vscode_ext) {
30+
switch (plugin) {
31+
case 'prettier-plugin-packagejson':
32+
return plugin_packagejson;
33+
case '@prettier/plugin-ruby':
34+
return plugin_ruby;
35+
}
36+
} else {
37+
/**
38+
* vscode's prettier extension fails to load esm plugins when they include
39+
* an esm import (https://github.com/prettier/prettier-vscode/issues/3066)
40+
* so we resolve the package's path here instead.
41+
*/
42+
return (
43+
import.meta
44+
.resolve(plugin)
45+
/**
46+
* vscode's prettier ext can't understand URIs, so we must convert
47+
* the URI to an absolute path instead.
48+
*/
49+
.replace(/^file:\/\//u, '')
50+
);
51+
}
52+
}
53+
2354
const option_sets: Record<string, Config | RubyConfig> = {
2455
general: {
2556
singleQuote: true,
@@ -52,12 +83,12 @@ const option_sets: Record<string, Config | RubyConfig> = {
5283

5384
package_json: {
5485
// TODO(0): consider switching to `prettier-plugin-pkg`
55-
plugins: [plugin_packagejson],
86+
plugins: [resolve_plugin('prettier-plugin-packagejson')],
5687
},
5788

5889
ruby: is_prettier_gem_installed
5990
? {
60-
plugins: [plugin_ruby],
91+
plugins: [resolve_plugin('@prettier/plugin-ruby')],
6192

6293
rubySingleQuote: true,
6394
// rubyPlugins: ['plugin/single_quotes'],

0 commit comments

Comments
 (0)