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

问题描述 投票:0回答:3

我在

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

"type": "module"
添加到 package.json 后(使用节点中的导入/导出语法enable),运行 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.

我正在使用 SublimeText 3 和 JSPrettier,它也停止工作,因为 prettier 不起作用。

es6-modules prettier
3个回答
12
投票

发生这种情况是因为在package.json中添加

"type": "module"
使得所有
.js
文件成为ES模块,然后它们只能在其他ES模块中导入。

Prettier 无法导入

prettier.config.js
,因为它现在是 ES 模块。

要解决此问题,请避免使用 Prettier 尝试从中导入的

.js
文件。相反,您可以在非
.js
文件中定义更漂亮的配置。从 prettier docs 有几个选项,例如使用
.prettierrc.json
文件或只是将 prettier 配置放入
package.json


6
投票

此外,您还可以使用

cjs
文件扩展名来指示它是 CommonJS 模块。

这将允许您继续使用插件的

require()
(在
*.json
配置文件中不可用。)。

文件名可以是

.prettierrc.cjs
,如 prettier 文档中所述。


0
投票

我在更漂亮的问题页面中找到的这个解决方案对我有用。只需将

.prettierrc.js
更改为
.prettierrc.json
即可。 评论链接

© www.soinside.com 2019 - 2024. All rights reserved.