6

I have defined a prettier config in prettier.config.js.

After adding "type": "module" to package.json (to enable using import/export syntax in node), running prettier fails with the following error:

Checking formatting...
[error] Invalid configuration file `prettier.config.js`: Must use import to load ES Module: /your/project/path/prettier.config.js
[error] require() of ES modules is not supported.
[error] require() of /your/project/path/prettier.config.js from /your/project/path/node_modules/prettier/third-party.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
[error] Instead rename prettier.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /your/project/path/package.json.
[error] 
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I'm using SublimeText 3 with JSPrettier, and it stops working too since prettier doesn't work.

ArneHugo
  • 6,051
  • 1
  • 26
  • 47

2 Answers2

6

This happens because adding "type": "module" in package.json makes all .js files ES modules, and then they can only be imported in other ES modules.

Prettier is not able to import prettier.config.js because it is now an ES module.

To fix this, avoid having a .js file that prettier tries to import from. Instead, you can define the prettier config in a non-.js file. From the prettier docs there are several options, such as using a .prettierrc.json file or just putting the prettier config into package.json.

ArneHugo
  • 6,051
  • 1
  • 26
  • 47
3

Also, you can use the cjs file extension to indicate it's a CommonJS module.

This will allow you to continue using the require() of plugins (not available in *.json configuration files.).

The file name could be .prettierrc.cjs as stated in prettier docs.