如何把uniapp项目打包为桌面应用

分享
已结 精华 置顶
0 1607
chichu
chichu 2023-09-05

1、在控制台安装electron

cnpm install electron -g


2、在控制台安装electron-packager

cnpm install electron-packager -g


3、修改uniapp的manifest.json,修改内容如下图所示:

运行的基础路径修改为:./  不然打包出来会出现白屏,读取不到,因为打包出来的h5默认加载地址为/static/
去掉启用https协议: 不然会出现网络无法加载,去掉https不影响你请求后端的https协议。

4、H5打包,如下图所示:


5、H5文件夹下新建package.json和main.js

package.json 的内容如下:

{
	"name":"我的应用",
	"version":"2.0",
	"main":"main.js",
	"scripts":{
		"test":"echo \"Error: no test specified\" && exit 1",
		"electron":"electron .",
		"start":"electron .",
		"build":"electron-packager ./ 我的应用 --plantform=win32 --arch=x64 --out 我的应用 --overwrite --icon=xdt.ico"
	},
	"author":"",
	"license":"ISC",
	"devDependencies":{
		"electron":"^23.3.13",
		"electron-packager":"^12.2.0"
	}
}

main.js 的内容如下:

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
 
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
 
function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({width: 400, height: 700})
 
  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
 
  // Open the DevTools.
  // win.webContents.openDevTools()
 
  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}
 
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
 
// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
 
app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})
 
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
如果你的网页首页的文件名不是 “index.html”,那么请在 main.js 中将其中的 'index.html' 修改为你的网页首页名。


6、打包,在项目目录下打开控制台,输入:

npm run build

如果出现如下报错:

Cannot find module ‘electron’
解决方案:cmd中输入:
npm install --save-dev electron。

【打包慢,无反应】

更换为阿里镜像源 命令行下输入


#设置阿里镜像源
npm config set registry http://registry.npmmirror.com 
切换到淘宝源,然后打包就好了。



上一篇:CLTPRO v3.0 发布

下一篇:关于TP6异步请求没返回数据的处理方法

回帖
取消评论