prettier / prettier-vscode

Visual Studio Code extension for Prettier
https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
MIT License
5.04k stars 446 forks source link

Cannot use `import` in `prettier.config.js` with Prettier v3 and ESM #3066

Open risu729 opened 10 months ago

risu729 commented 10 months ago

Summary

Format fails if prettier.config.js is written in ESM and contains import for plugins.

Github Repository to Reproduce Issue

https://github.com/risu729/prettier-test

Steps To Reproduce:

  1. Create prettier.config.js with {"type": "module"} containing import like below.
    
    import organizeImports from "prettier-plugin-organize-imports";

export default { plugins: [organizeImports], };

2. Run format for a file.

### Expected result

Format the file successfully.

### Actual result

Failed with error: `Error resolving prettier configuration for $path`
However, `npm exec prettier --write .` runs successfully.

If I change the filename to `prettier.config.mjs`, regardless of `type` in `package.json`, prettier fails.

### Additional information

**VS Code Version**:
Version: 1.81.0-insider (user setup)
Commit: 79ec05cb73486ad2d57a57a5f138b094d21c8644
Date: 2023-07-06T23:18:22.645Z
Electron: 22.3.14
ElectronBuildId: 21893604
Chromium: 108.0.5359.215
Node.js: 16.17.1
V8: 10.8.168.25-electron.0
OS: Windows_NT x64 10.0.23493

**Prettier Extension Version**: 9.19.0

**OS and version**: Windows 11 Home Insider Preview 22H2

## Prettier Log Output

For `prettier.config.js`,

["INFO" - 1:01:56 PM] Formatting file:///c%3A/Users/taku/Documents/GitHub/prettier-test/prettier.config.js ["DEBUG" - 1:01:56 PM] Local prettier module path: 'c:\Users\taku\Documents\GitHub\prettier-test\node_modules\prettier\index.cjs' ["ERROR" - 1:01:56 PM] Error resolving prettier configuration for c:\Users\taku\Documents\GitHub\prettier-test\prettier.config.js ["ERROR" - 1:01:56 PM] require() of ES Module c:\Users\taku\Documents\GitHub\prettier-test\prettier.config.js from C:\Users\taku\Documents\GitHub\prettier-test\node_modules.pnpm\prettier@3.0.0\node_modules\prettier\internal\internal.mjs not supported. Instead change the require of prettier.config.js in C:\Users\taku\Documents\GitHub\prettier-test\node_modules.pnpm\prettier@3.0.0\node_modules\prettier\internal\internal.mjs to a dynamic import() which is available in all CommonJS modules. Error [ERR_REQUIRE_ESM]: require() of ES Module c:\Users\taku\Documents\GitHub\prettier-test\prettier.config.js from C:\Users\taku\Documents\GitHub\prettier-test\node_modules.pnpm\prettier@3.0.0\node_modules\prettier\internal\internal.mjs not supported. Instead change the require of prettier.config.js in C:\Users\taku\Documents\GitHub\prettier-test\node_modules.pnpm\prettier@3.0.0\node_modules\prettier\internal\internal.mjs to a dynamic import() which is available in all CommonJS modules. at f._load (node:electron/js2c/asar_bundle:2:13330) at module.exports (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:173:34) at loadJsSync2 (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5394:22) at loadJs2 (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5404:16) at async Explorer.loadFileContent (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5763:18) at async Explorer.createCosmiconfigResult (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5770:29) at async Explorer.loadSearchPlace (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5752:16) at async Explorer.searchDirectory (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5742:31) at async run (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5728:26) at async Explorer.search (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/internal/internal.mjs:5723:16) at async Module.resolveConfigFile (file:///C:/Users/taku/Documents/GitHub/prettier-test/node_modules/.pnpm/prettier@3.0.0/node_modules/prettier/index.mjs:20333:18)


For `prettier.config.mjs`, the error object seems empty.

["INFO" - 2:29:40 PM] Formatting file:///c%3A/Users/taku/Documents/GitHub/prettier-test/prettier.config.mjs ["DEBUG" - 2:29:40 PM] Local prettier module path: 'c:\Users\taku\Documents\GitHub\prettier-test\node_modules\prettier\index.cjs' ["DEBUG" - 2:29:40 PM] Using prettier version 3.0.0 ["ERROR" - 2:29:40 PM] Invalid prettier configuration file detected. {} ["ERROR" - 2:29:40 PM] Invalid prettier configuration file detected. See log for details.

zkulbeda commented 10 months ago

Cosmiconfig uses require as fallback when esm module import throws error. I manually edited prettier in node_modules to throw instead of fallback and got this error

["ERROR" - 18:32:33] Error resolving prettier configuration for /home/ubuntu/workspace/UsersSearchBot
["ERROR" - 18:32:33] Cannot find package 'prettier-plugin-tailwind' imported from /home/ubuntu/workspace/UsersSearchBot/prettier.config.mjs
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'prettier-plugin-tailwind' imported from /home/ubuntu/workspace/UsersSearchBot/prettier.config.mjs
    at new NodeError (node:internal/errors:387:5)
    at packageResolve (node:internal/modules/esm/resolve:951:9)
    at moduleResolve (node:internal/modules/esm/resolve:1000:20)
    at defaultResolve (node:internal/modules/esm/resolve:1214:11)
    at nextResolve (node:internal/modules/esm/loader:165:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:844:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:431:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36)

My prettier.config.js

import tailwind from "prettier-plugin-tailwindcss";

/** @type {import("prettier").Options} */
export default {
  printWidth: 80,
  trailingComma: "all",
  htmlWhitespaceSensitivity: "css",
  plugins: [tailwind],
}; 

Seems prettier vscode plugin can't resolve imports from prettier config. I'm using pnpm as package manager and got same error if using imports from my config. If I remove imports from config, the error will disappear This error appears when cosmiconfig import ends up with error.

michaelhays commented 10 months ago

@zkulbeda I noticed the error message says 'prettier-plugin-tailwind' instead of 'prettier-plugin-tailwindcss', is that the most recent error message?

zkulbeda commented 10 months ago

Oh, seems plugin can't load new config, and on every attempt tries import old file. I use Developer: Restart Extension Host to reload config and it's working. The import error disappear, but there is another one image I deleted node_modules and install depencies to wipe my changes. pnpm prettier --write . runs without error

michaelhays commented 10 months ago

Got it, yep that's the exact same error I'm getting.

zkulbeda commented 10 months ago

@michaelhays did you solve the problem? I didn't. We should open another issue if so

michaelhays commented 10 months ago

I think it's the same issue as this one -- the error only happens for me when using ESM import.

I was able to make it work for now by using CommonJS for this file instead, by naming it prettier.config.cjs:

/** @type {import("prettier").Options} */
module.exports = {
  semi: false,
  singleQuote: true,
  plugins: ['prettier-plugin-tailwindcss'],
}
zkulbeda commented 10 months ago

Hm, it also works with esm without import. So I suppose the problem isn't about esm

/** @type {import("prettier").Options} */
export default {
    printWidth: 80,
    trailingComma: "all",
    htmlWhitespaceSensitivity: "css",
    plugins: ["prettier-plugin-tailwindcss"],
};
hisham commented 10 months ago

My prettier config is in package.json. 2.8.8 works fine. Upgrading to prettier 3.0 makes this plugin fail with following error:

["DEBUG" - 9:49:41 AM] Local prettier module path: '/Users/hisham/src/ess-app/node_modules/prettier'
["DEBUG" - 9:49:41 AM] Using prettier version 3.0.0
["ERROR" - 9:49:41 AM] Error resolving prettier configuration for /Users/hisham/src/ess-app
["ERROR" - 9:49:41 AM] Invalid host defined options
TypeError: Invalid host defined options
    at Object.<anonymous> (/Users/hisham/src/ess-app/node_modules/prettier/index.cjs:600:23)

Running prettier from command line works fine.

tebuevd commented 9 months ago

Getting the same error when on prettier@3 with the following config:

//prettier.config.js

/** @type {import('prettier').Config} */
module.exports = {
  trailingComma: "all",
  tabWidth: 2,
  semi: false,
  plugins: [require("prettier-plugin-tailwindcss")],
  tailwindConfig: "./packages/configs/tailwind/tailwind.config.js",
  tailwindAttributes: [
    "modalStyles",
    "titleStyles",
    "subtitleStyles",
    "iconStyles",
  ],
  tailwindFunctions: ["clsx", "cn"],
}
mironote commented 9 months ago

getting the save error with prettier@3 on vscode

["ERROR" - 09:47:27] Error handling text editor change
["ERROR" - 09:47:27] Invalid host defined options
TypeError: Invalid host defined options
    at Object.<anonymous> (/Users/fengxing/miro/mironote/node_modules/prettier/index.cjs:600:23)
    at Module.u._compile (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/loader.js:4:1271)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1243:10)
    at Module.load (node:internal/modules/cjs/loader:1058:32)
    at Module._load (node:internal/modules/cjs/loader:893:12)
    at Function.f._load (node:electron/js2c/asar_bundle:2:13330)
    at Function.l._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:127:28070)
    at Function.p._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:127:25404)
    at Function.u._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:91:22191)
    at Module.require (node:internal/modules/cjs/loader:1082:19)
    at g (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/loader.js:4:647)
    at t.loadNodeModule (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:2829)
    at t.PrettierMainThreadInstance.import (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:17760)
    at t.ModuleResolver.getPrettierInstance (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:5728)
    at t.default.handleActiveTextEditorChanged (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:10771)
    at t.default.handleActiveTextEditorChangedSync (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:10373)
    at t.default.registerDisposables (/Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:13531)
    at /Users/fengxing/.vscode/extensions/esbenp.prettier-vscode-9.19.0/dist/extension.js:1:82528
gawlk commented 9 months ago

Getting the same error when on prettier@3 with the following config:

//prettier.config.js

/** @type {import('prettier').Config} */
module.exports = {
  trailingComma: "all",
  tabWidth: 2,
  semi: false,
  plugins: [require("prettier-plugin-tailwindcss")],
  tailwindConfig: "./packages/configs/tailwind/tailwind.config.js",
  tailwindAttributes: [
    "modalStyles",
    "titleStyles",
    "subtitleStyles",
    "iconStyles",
  ],
  tailwindFunctions: ["clsx", "cn"],
}

@tebuevd

I didn't try your exact config but had the issue with plugins: [require("prettier-plugin-tailwindcss")],. Changing it to plugins: ['prettier-plugin-tailwindcss'], worked

crklan commented 9 months ago

I'm experiencing the same problem as described above. My config file .prettierrc.js looks like this:

module.exports = {
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": true,
    "singleQuote": true,
    "singleAttributePerLine": false,
    "bracketSpacing": true,
    "plugins": [
        require("prettier-plugin-organize-attributes"),
    ],
}

If require is removed, the prettier doesn't work from the CLI, as I'm using Git hooks to format the code on precommit and I get the same error as in this issue.

ChristianIvicevic commented 9 months ago

I am working in a monorepo and trying to compose the prettier config. At root level I have this file:

/** @type import('prettier').Config */
export default {
  printWidth: 110,
  endOfLine: 'auto',
  singleQuote: true,
  trailingComma: 'none'
};

In one of my apps within the monorepo I was attempting this

import baseConfig from '../../prettier.config.mjs';

/** @type import('prettier').Config */
export default {
  ...baseConfig,
  plugins: ['prettier-plugin-tailwindcss'],
  tailwindConfig: 'tailwind.config.mjs',
  tailwindFunctions: ['cn']
};

This was failing with the following error message

[error] Invalid configuration for file "src/app/components.client.tsx":
[error] require() of ES Module prettier.config.mjs not supported.
[error] Instead change the require of prettier.config.mjs to a dynamic import() which is available in all CommonJS modules.

Only after researching the issue thoroughly I stumbled upon this thread and noticed that I have to remove the import for now which makes the config not composable, sadly.

semihraifgurel commented 9 months ago

@gawlk

I didn't try your exact config but had the issue with plugins: [require("prettier-plugin-tailwindcss")],. Changing it to plugins: ['prettier-plugin-tailwindcss'], worked

Thank you, when I do this it runs smoothly.

const config = {
    plugins: ['prettier-plugin-tailwindcss'],
    printWidth: 100,
    tabWidth: 4,
    useTabs: true,
    semi: true,
    singleQuote: true,
    jsxSingleQuote: true,
    trailingComma: 'all',
    bracketSameLine: true,
    arrowParens: 'always',
    endOfLine: 'lf',
};

module.exports = config;
elie222 commented 8 months ago

Wasn't able to get any of the above working. We also use pretty-quick so that may be the cause. Reverting to "prettier-plugin-tailwindcss": "^0.4.1", for now.

ethernal commented 8 months ago

For me when using NextJS 13 with latest prettier, neither .cjs or .js worked but changing config file to .ts fixed the issue.

// prettier.config.ts
/** @type {import('prettier').Config} */
module.exports = {
  semi: true,
  singleQuote: true,
  plugins: ['prettier-plugin-tailwindcss'],
};
liamlows commented 8 months ago

For me when using NextJS 13 with latest prettier, neither .cjs or .js worked but changing config file to .ts fixed the issue.

// prettier.config.ts
/** @type {import('prettier').Config} */
module.exports = {
  semi: true,
  singleQuote: true,
  plugins: ['prettier-plugin-tailwindcss'],
};

I have been searching for a solution to this for ages! Thank you so much for sharing, this worked for me!

Spikatrix commented 8 months ago

Changing plugins: ['plugin-name'] to plugins: [require.resolve('plugin-name')] works for me in both vscode and precommit

risu729 commented 7 months ago

For me, prettier.config.cjs with plugins: [require.resolve('plugin-name')] like below worked for both the vscode extension and CLI.

Using prettier.config.ts resolved the error; however, the plugin did not work. Also, plugins: ['plugin-name'] and plugins: [require('plugin-name')] didn't throw errors, but the plugin didn't work.

module.exports = {
  plugins: [require.resolve("prettier-plugin-organize-imports")],
};
Aszurar commented 7 months ago

Getting the same error when on prettier@3 with the following config:

//prettier.config.js

/** @type {import('prettier').Config} */
module.exports = {
  trailingComma: "all",
  tabWidth: 2,
  semi: false,
  plugins: [require("prettier-plugin-tailwindcss")],
  tailwindConfig: "./packages/configs/tailwind/tailwind.config.js",
  tailwindAttributes: [
    "modalStyles",
    "titleStyles",
    "subtitleStyles",
    "iconStyles",
  ],
  tailwindFunctions: ["clsx", "cn"],
}

@tebuevd

I didn't try your exact config but had the issue with plugins: [require("prettier-plugin-tailwindcss")],. Changing it to plugins: ['prettier-plugin-tailwindcss'], worked

Thanks, solved it here by removing the require

viceice commented 7 months ago

doesn't work for me:

Invalid prettier configuration file detected.

// .prettierrc.cjs
/** @type {import("prettier").Options} */
module.exports = {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [require('prettier-plugin-packagejson')],
};

require() of ES Module ~\gh\containerbase\maven-prebuild\.prettierrc.mjs not supported.

import pkgJson from 'prettier-plugin-packagejson';

/** @type {import("prettier").Options} */
export default {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [pkgJson],
};
risu729 commented 7 months ago

@viceice

Could you try using require.resolve like this? It worked for me.

// .prettierrc.cjs
/** @type {import("prettier").Options} */
module.exports = {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [require.resolve('prettier-plugin-packagejson')],
};
viceice commented 7 months ago
// .prettierrc.cjs
/** @type {import("prettier").Options} */
module.exports = {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [require.resolve('prettier-plugin-packagejson')],
};

no: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

BTW: I'm using yarn pnp mode

risu729 commented 7 months ago

I have no idea about yarn pnp... I'm using pnpm.

blikblum commented 7 months ago

I'm getting an slight different error: A dynamic import callback was not specified. Is related with a project configured as module type

In this repo.

I dont use import or require in the prettier config. Its just json (.prettierrc):

{
  "singleQuote": true,
  "semi": false,
  "endOfLine": "auto",
  "printWidth": 100
}

The project is configured as type: module in package.json

When i change the project type to commonjs, the config file is loaded normally and prettier works

Error callstack


["INFO" - 8:09:13 AM] Extension Name: esbenp.prettier-vscode.
["INFO" - 8:09:13 AM] Extension Version: 10.1.0.
["INFO" - 8:13:53 AM] Formatting file:///home/luiz/repositories/nextbone-bootstrap-starter/vite.config.js
["ERROR" - 8:13:53 AM] Error resolving prettier configuration for /home/luiz/repositories/nextbone-bootstrap-starter/vite.config.js
["ERROR" - 8:13:53 AM] A dynamic import callback was not specified.
TypeError: A dynamic import callback was not specified.
    at new NodeError (node:internal/errors:399:5)
    at importModuleDynamicallyCallback (node:internal/process/esm_loader:39:9)
    at Object.<anonymous> (/home/luiz/repositories/nextbone-bootstrap-starter/node_modules/prettier/index.cjs:600:23)
    at Module.u._compile (/usr/share/code/resources/app/out/vs/loader.js:4:1271)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1371:10)
    at Module.load (node:internal/modules/cjs/loader:1171:32)
    at Module._load (node:internal/modules/cjs/loader:1012:12)
    at Function.f._load (node:electron/js2c/asar_bundle:2:13377)
    at Function.u._load (/usr/share/code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:153:5631)
    at Function.c._load (/usr/share/code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:150:29196)
    at Function.t._load (/usr/share/code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:117:35261)
    at Module.require (node:internal/modules/cjs/loader:1195:19)
    at Module.require (/home/luiz/.vscode/extensions/ms-edgedevtools.vscode-edge-devtools-2.1.3/out/extension.js:1:781704)
    at g (/usr/share/code/resources/app/out/vs/loader.js:4:647)
    at t.loadNodeModule (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:2829)
    at t.PrettierMainThreadInstance.import (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:17760)
    at t.ModuleResolver.getPrettierInstance (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:5728)
    at t.ModuleResolver.getResolvedConfig (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:7496)
    at t.default.format (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:14589)
    at t.PrettierEditProvider.provideEdits (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:12683)
    at t.PrettierEditProvider.provideDocumentFormattingEdits (/home/luiz/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:8922)
`
myleslee commented 7 months ago
// .prettierrc.cjs
/** @type {import("prettier").Options} */
module.exports = {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [require.resolve('prettier-plugin-packagejson')],
};

no: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:' BTW: I'm using yarn pnp mode

hey, did you end up finding a fix for this? we're having the same exact issue with yarn pnp

Restarting the VSCode after require.resolve() was applied fixed my issue.

CamaleonGamer commented 6 months ago
// .prettierrc.cjs
/** @type {import("prettier").Options} */
module.exports = {
  singleQuote: true,
  trailingComma: 'all',
  plugins: [require.resolve('prettier-plugin-packagejson')],
};

no: Only URLs with a scheme in: file and data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:' BTW: I'm using yarn pnp mode

hey, did you end up finding a fix for this? we're having the same exact issue with yarn pnp

Restarting the VSCode after require.resolve() was applied fixed my issue.

I had the same problem and it was fixed by restarting vscode

90dy commented 6 months ago

@gawlk I didn't try your exact config but had the issue with plugins: [require("prettier-plugin-tailwindcss")],. Changing it to plugins: ['prettier-plugin-tailwindcss'], worked

Thank you, when I do this it runs smoothly.

const config = {
  plugins: ['prettier-plugin-tailwindcss'],
  printWidth: 100,
  tabWidth: 4,
  useTabs: true,
  semi: true,
  singleQuote: true,
  jsxSingleQuote: true,
  trailingComma: 'all',
  bracketSameLine: true,
  arrowParens: 'always',
  endOfLine: 'lf',
};

module.exports = config;

This is the solution for prettier@^3

iamandrewluca commented 5 months ago

The solution for me was to remove node_modules and run npm install again and reload the VSCode.

PS: Whenever prettier related stuff is changed, is better to reload the VSCode to get the new changes.

vincerubinetti commented 5 months ago

Using the ESM config example straight from the docs (from my default config in my home directory) throws this error:

["ERROR" - 2:38:44 PM] Error resolving prettier configuration for /Users/vincerubinetti/.prettierrc.js
["ERROR" - 2:38:44 PM] Invalid or unexpected token
/Users/vincerubinetti/.prettierrc.js:1
(function (exports, require, module, __filename, __dirname) { ��c

SyntaxError: Invalid or unexpected token

~Have to use commonjs it seems.~ Actually this throws basically the same error. So this extension basically just doesn't work at all, in any capacity lol.

iamandrewluca commented 5 months ago

Actually this throws basically the same error. So this extension basically just doesn't work at all, in any capacity lol.

@vincerubinetti Mostly you did not configure something right. Extension basically just does what is supposed to do.

image image image
vincerubinetti commented 5 months ago

@vincerubinetti Mostly you did not configure something right. Extension basically just does what is supposed to do.

@iamandrewluca Nope. My extension has all the default settings (no prettier. entries in settings.json), and I simply have export default {} in ~/.prettierrc.js (UTF-8 encoded), and a it throws an error (same thing with prettier.config.js). This may have something to do with the fact that I am trying to format files that are not in a directory with a package.json that defines a type. Naming the file .prettierrc.mjs or prettier.config.mjs, the extension just doesn't even detect it.

karlhorky commented 3 months ago

Crash description + reproduction

@ntotten @sosukesuzuki The Prettier VS Code extension (esbenp.prettier-vscode@10.1.0) currently crashes when:

  1. no prettier dependency installed in package.json
  2. "type": "module" in package.json
  3. prettier.config.js with ESM

Reproduction repo: https://github.com/karlhorky/prettier-vscode-10-1-0-esm-crash

["INFO" - 5:28:43 PM] Extension Name: esbenp.prettier-vscode.
["INFO" - 5:28:43 PM] Extension Version: 10.1.0.
["INFO" - 5:28:53 PM] Formatting file:///Users/k/p/prettier-vscode-10-1-0-esm-crash/index.js
["ERROR" - 5:28:53 PM] Error resolving prettier configuration for /Users/k/p/prettier-vscode-10-1-0-esm-crash/index.js
["ERROR" - 5:28:53 PM] require() of ES Module /Users/k/p/prettier-vscode-10-1-0-esm-crash/prettier.config.js from /Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js not supported.
Instead change the require of prettier.config.js in /Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js to a dynamic import() which is available in all CommonJS modules.
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/k/p/prettier-vscode-10-1-0-esm-crash/prettier.config.js from /Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js not supported.
Instead change the require of prettier.config.js in /Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js to a dynamic import() which is available in all CommonJS modules.
    at Function.<anonymous> (node:electron/js2c/asar_bundle:2:13327)
    at l._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:173:5635)
    at r._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:170:29791)
    at t._load (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:135:35292)
    at Module.patchedRequire [as require] (/Users/k/.vscode/extensions/github.copilot-1.156.0/dist/extension.js:104:43169)
    at module2.exports (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:83:61)
    at loadJs2 (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8050:22)
    at Explorer.loadFileContent (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8449:36)
    at Explorer.createCosmiconfigResult (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8453:40)
    at Explorer.loadSearchPlace (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8438:35)
    at async Explorer.searchDirectory (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8428:31)
    at async run (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8413:26)
    at async Explorer.search (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/third-party.js:8407:24)
    at async Object.resolveConfigFile (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/node_modules/prettier/index.js:18499:22)
    at async t.ModuleResolver.resolveConfig (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:6697)
    at async t.ModuleResolver.getResolvedConfig (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:7529)
    at async t.default.format (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:14563)
    at async t.PrettierEditProvider.provideEdits (/Users/k/.vscode/extensions/esbenp.prettier-vscode-10.1.0/dist/extension.js:1:12672)
    at async z.provideDocumentFormattingEdits (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/api/node/extensionHostProcess.js:150:93866)

Screenshot 2024-02-05 at 17 45 30


Cause

This is because the VS Code extension uses the old Prettier v2 internally - because the PR from @sosukesuzuki upgrading to Prettier v3 by default was reverted:

...and Prettier v2 (prettier@2.8.8) also breaks with a similar error:

$ pnpm prettier --version      
2.8.8
$ pnpm prettier index.js --write                  
[error] Invalid configuration file `index.js`: require() of ES Module /Users/k/p/prettier-vscode-10-1-0-esm-crash/prettier.config.js from /Users/k/p/prettier-vscode-10-1-0-esm-crash/node_modules/.pnpm/prettier@2.8.8/node_modules/prettier/third-party.js not supported.
[error] Instead change the require of prettier.config.js in /Users/k/p/prettier-vscode-10-1-0-esm-crash/node_modules/.pnpm/prettier@2.8.8/node_modules/prettier/third-party.js to a dynamic import() which is available in all CommonJS modules.

Workaround

Add Prettier v3 to your dependencies in every project 😬

{
  "type": "module",
  "main": "index.js",
  "dependencies": {
+    "prettier": "3.2.5"
  }
}

Fix

@ntotten would you accept a new PR upgrading to Prettier v3 by default in the Prettier VS Code extension?

karlhorky commented 3 months ago

Just saw that this issue has "Prettier v3" in the title, whereas the VS Code extension is not yet on Prettier v3 internally (hopefully soon!).

I created a new issue over here:

github-actions[bot] commented 1 month ago

This issue has been labeled as stale due to inactivity. Reply to keep this issue open.

karlhorky commented 1 month ago

I guess this hasn't been resolved yet.

flying-sheep commented 1 month ago

Also the bot malfunctions. You replied and the [stale] is still there