在初始化vite3 + vue3項(xiàng)目安裝eslint時(shí)報(bào)錯(cuò)如下:
[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).
在分析官方提示后發(fā)現(xiàn)應(yīng)該在package.json文件中修改type為commonjs或?qū)?eslintrc.js文件名改為.eslintrc.cjs便可解決該問題
原因分析:
-
type字段的產(chǎn)生用于定義package.json文件和該文件所在目錄根目錄中.js文件和無拓展名文件的處理方式。值為'moduel'則當(dāng)作es模塊處理;值為'commonjs'則被當(dāng)作commonJs模塊處理 - 目前
node默認(rèn)的是如果pacakage.json沒有定義type字段,則按照commonJs規(guī)范處理 -
node官方建議包的開發(fā)者明確指定package.json中type字段的值 - 無論
package.json中的type字段為何值,.mjs的文件都按照es模塊來處理,.cjs的文件都按照commonJs模塊來處理