prettier-vscode: Cannot use `import` in `prettier.config.js` with Prettier v3 and ESM

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],
};
  1. 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.

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Reactions: 42
  • Comments: 37 (3 by maintainers)

Commits related to this issue

Most upvoted comments

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'],
}

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

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.

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'],
};

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

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!

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?

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.

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

// .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ā€™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)
`

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

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")],
};

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.

Got it, yep thatā€™s the exact same error Iā€™m getting.

// .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

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

@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;