Electron 打包工具有很多,如Electron-build、 Electron Forge 等,这里使用Electron-build,而Electron-build使用了nsis组件来创建安装向导,默认情况nsis安装向导不能自定义安装向导界面,但是nsis提供了nsis脚本可以扩展安装向导。
0.效果图
1.配置nsis脚本
在新建nsis脚本文件resources/installer.nsh,并添加自定义内容:
!define MUI_LANGUAGE "Chinese"
Unicode true!include nsDialogs.nsh
!include LogicLib.nsh#OutFile nsDialogs.exe
#RequestExecutionLevel user
#ShowInstDetails showVar Dialog
Var apiUrl
Var other1
Var other2
Var other3
Var other4
Var skipSetPage custom pgPageCreate pgPageLeaveFunction pgPageCreatensDialogs::Create 1018Pop $Dialog${If} $Dialog == errorAbort${EndIf}${NSD_CreateGroupBox} 10% 10u 80% 100u "接入地址配置"Pop $0${NSD_CreateLabel} 20% 26u 20% 10u "接入地址:"Pop $0${NSD_CreateText} 40% 24u 40% 12u ""Pop $apiUrl${NSD_CreateLabel} 20% 40u 20% 10u "其他配置1:"Pop $0${NSD_CreateText} 40% 38u 40% 12u ""Pop $other1${NSD_CreateLabel} 20% 54u 20% 10u "其他配置2:"Pop $0${NSD_CreateText} 40% 52u 40% 12u ""Pop $other2${NSD_CreateLabel} 20% 68u 20% 10u "其他配置3:"Pop $0${NSD_CreateText} 40% 66u 40% 12u ""Pop $other3${NSD_CreateLabel} 20% 82u 20% 10u "其他配置4:"Pop $0${NSD_CreateText} 40% 80u 40% 12u ""Pop $other4${NSD_CreateCheckbox} 20% 96u 100% 10u "跳过当前设置"Pop $skipSetnsDialogs::Show
FunctionEndFunction PgPageLeave${NSD_GetText} $apiUrl $0${NSD_GetText} $other1 $1${NSD_GetText} $other2 $2${NSD_GetText} $other3 $3${NSD_GetText} $other4 $4${NSD_GetState} $skipSet $6;将配置信息写入文件: C:\用户\用户名\AppData\Roaming\demo\config.json${If} $6 == 0SetOutPath "$APPDATA\demo"CreateDirectory "$APPDATA\demo";FileOpen $9 $APPDATA\demo\config.json w;FileWrite $9 '{"apiUrl":"$0","other1":"$1","other2":"$2","other3":"$3","other4":"$4"}';FileClose $9;SetFileAttributes $APPDATA\demo\config.json NORMALStrCpy $0 '{"apiUrl":"$0","other1":"$1","other2":"$2","other3":"$3","other4":"$4"}'FileOpen $5 "$APPDATA\demo\config.json" "w"FileWrite $5 $0FileClose $5${EndIf}FunctionEndSection
SectionEnd
2.在package.json添加nsis脚本
在package.json的build中的nsis添加我们自定义nsis脚本的引用:"include": "resources/installer.nsh"
,完整配置如下:
"build": {"appId": "com.demo.electron","productName": "Electron应用示例","copyright": "Copyright © Electron应用示例","mac": {"category": "public.app-category.utilities"},"win": {"icon": "./resources/icons/icon.ico","target": [{"target": "nsis","arch": ["ia32","x64"]}],"artifactName": "${productName}_${version}-${arch}.${ext}"},"nsis": {"oneClick": false,"allowElevation": true,"allowToChangeInstallationDirectory": true,"installerIcon": "./resources/icons/icon.ico","uninstallerIcon": "./resources/icons/icon.ico","installerHeaderIcon": "./resources/icons/icon.ico","createDesktopShortcut": true,"createStartMenuShortcut": true,"shortcutName": "Electron应用示例","runAfterFinish": true,"include": "resources/installer.nsh"},"files": ["dist/**/*","dist-electron/**/*"],"directories": {"buildResources": "assets","output": "dist-build"},"publish": [{"provider": "generic","url": "http://192.168.1.2/release/"}],"extraResources": ["./plugins/${platform}/${arch}/**"]},
3.打包
执行打包命令:
npm run electron:build.exe
打包完双击安装包就有效果了。