在初始化vite3 + vue3项目安装eslint时报错如下:
[vite] Internal server error: Cannot read config file: D:\vue3-template\.eslintrc.js
Error: require() of ES Module D:\vue3-template\.eslintrc.js from D:\vue3-template\node_modules\@eslint\eslintrc\dist\eslintrc.cjs not supported.
.eslintrc.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 .eslintrc.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 D:\vue3-template\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
在分析官方提示后发现应该在package.json文件中修改type为commonjs或将.eslintrc.js文件名改为.eslintrc.cjs便可解决该问题
原因分析:
-
type
字段的产生用于定义package.json
文件和该文件所在目录根目录中.js
文件和无拓展名文件的处理方式。值为'moduel'
则当作es模块处理;值为'commonjs'
则被当作commonJs
模块处理 - 目前
node
默认的是如果pacakage.json
没有定义type
字段,则按照commonJs
规范处理 -
node
官方建议包的开发者明确指定package.json
中type
字段的值 - 无论
package.json
中的type字段为何值,.mjs
的文件都按照es
模块来处理,.cjs
的文件都按照commonJs
模块来处理