在 package.json 中声明 { "type": "module" } 时 Prettier 失败

Arn*_*ugo 9 es6-modules prettier

我在 中定义了一个更漂亮的配置prettier.config.js

"type": "module"添加到 package.json后(以启用在节点中使用导入/导出语法),运行 prettier 失败并出现以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

我将 SublimeText 3 与JSPrettier一起使用,它也停止工作,因为 prettier 不起作用。

Arn*_*ugo 11

发生这种情况是因为"type": "module"在package.json中添加使所有.js文件成为ES模块,然后它们只能在其他ES模块中导入。

Prettier 无法导入,prettier.config.js因为它现在是 ES 模块。

要解决此问题,请避免使用.jsPrettier 尝试从中导入的文件。相反,您可以在非文件中定义更漂亮的配置.js。从 prettier文档中有几个选项,例如使用.prettierrc.json文件或只是将 prettier 配置放入package.json.