vite在引入Prettier时使用.prettier.js配置文件不生效

2,040 阅读2分钟

最近在搭建项目的时候发现配置的prettier一直不生效。对照网上的配置发现好像并没有出错。那到底为啥呢

633170c0e7bce743424c659e.gif

既然发现不了就重装,卸载vscode,卸载prettier插件。折腾了一会,在重装后突然发现右下角prettier爆红了,点进去一看是node报错了。既然报错了那就说明在使用的时候出错了,先看看这条报错信息

require() of ES Module e:\xxx.prettierrc.js from XXX not supported.prettier.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead rename prettier.config.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in e:\xxx\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead). Occurred while linting

大意就是:不支持被视为ES模块的.pretierrc.js文件中的require方法。因为在这个项目中的package.json文件中声明了type: module。这样就把所有的js文件视作ES模块。请将.pretierrc.js的后缀名改为.cjs

9150e4e5gy1g6r4gbi90yj205i05idfm.jpg

看到这就知道了,是因为在package.json中声明了type:module,导致项目中的所有js文件被视作es模块,而在.prettier.js文件中却使用了module.exports,也就是commonJS规范

而我的项目使用vite创建的,在package.json中发现了type:module这一配置项,于是将.prettier.js改为.prettier.cjs发现Prettier可以正常使用了

至于为什么vite不支持CommonJS呢,这就涉及到vite底层原理了:

vite在运行时使用esbuild,它是基于esm来工作的。Vite 的开发服务器将所有代码视为原生 ES 模块。因此,Vite 必须先将作为 CommonJS 或 UMD 发布的依赖项转换为 ESM。也就是要使用commonJs,就要先将其预构建为es模块。此处详见vite官方文档依赖预构建这一章节