基础准备: Vue Electron Vite npm 等环境需要自行添加,有条件可以更改一下各自对应的源
项目搭建步骤
npm init vite
npm run dev
npm i electron -D
npm i nodemon -D
package.json中需要自行添加
"scripts": {
"start": "nodemon --exec electron . --watch ./ --ext .js,.html,.css,.vue"
},
start之后如果报错:
App threw an error during load
Error [ERR_REQUIRE_ESM]: require() of ES Module /xxxxx/Desktop/VUEAddElectron/readit/main.js from /Users/banma-3062/Desktop/VUEAddElectron/readit/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar/main.js not supported.
/Users/xxxx/Desktop/VUEAddElectron/readit/main.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 /Users/xxxx/Desktop/VUEAddElectron/readit/main.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 /Users/xxxx/Desktop/VUEAddElectron/readit/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
需要将package.json文件中type取值改为commonjs
在分析官方提示后发现应该在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模块来处理
网友评论