eslint 和 prettier 配置文件不能是 .js 文件,必须是.cjs 文件怎么回事 ?

用 vite 创建的 vue-ts 项目,初始化后,安装 Eslint 和 Prettier 依赖,然后执行

npx eslint --init

自动生成的是 .eslintrc.cjs 文件,开始没在意这个细节 !

紧接着安装 Prettier 后手动创建配置文件 prettier.config.js 发现 Eslint 报错

require() of ES Module F:\WorkStation\vueProgram\mxWechat\prettier.config.js from F:\WorkStation\vueProgram\mxWechat\node_modules\prettier\third-party.js not supported. prettier.config.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 F:\WorkStation\vueProgram\mxWechat\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).  Occurred while linting F:\WorkStation\vueProgram\mxWechat\src\App.vue:4 Rule: "prettier/prettier"
require() of ES Module F:\WorkStation\vueProgram\mxWechat\prettier.config.js from F:\WorkStation\vueProgram\mxWechat\node_modules\prettier\third-party.js not supported. prettier.config.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 F:\WorkStation\vueProgram\mxWechat\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead). Occurred while linting F:\WorkStation\vueProgram\mxWechat\src\App.vue:4 Rule: "prettier/prettier"

将其扩展名改成 .cjs 重启 vscode 就可以,eslintrc.cjs 也是一样,改成 .js 扩展名后就包相同错误 …

怀疑是 node 版本问题,但也不对啊,其它项目就没问题,问题本身应该还是在 eslint、prettier 或者 vite 和 typescript 配置问题上 … 具体在哪不知道 !有遇到过的大神么 ?

阅读 15.3k
1 个回答

因为你的项目被创建为 ES module。你可以看下 package.json,里面应该有 type: module 的项目。

于是 .js 被默认为使用了 ES module 规范,如果自动生成的配置文件使用了 CommonJS,就会出错。.cjs 的 js 会告诉 node.js 它使用了 CommonJS 规范,所以就不会出错。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏