Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettier fails when declaring { "type": "module" } in package.json

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.

like image 617
ArneHugo Avatar asked Dec 06 '25 05:12

ArneHugo


2 Answers

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.

like image 146
ArneHugo Avatar answered Dec 10 '25 01:12

ArneHugo


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.

like image 22
DashDashDot Avatar answered Dec 10 '25 01:12

DashDashDot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!