将 HTML/CSS/JS 编辑器打包为 Windows 应用程序

• 3 分钟阅读 • web

使用 Electron打包markdown编辑器。

准备项目结构

markdown-editor/
├── index.html (之前的编辑器代码)
├── main.js
├── package.json
└── icons/ (可选)

创建 main.js (Electron 主进程文件)

const { app, BrowserWindow } = require('electron')
const path = require('path')
// 在主进程 (main.js) 中禁用不需要的功能
app.commandLine.appendSwitch('disable-3d-apis');
app.commandLine.appendSwitch('disable-gpu');
function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, 'icons/icon.ico') // 可选
  })

  win.loadFile('index.html')
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

初始化项目

在项目目录运行:

npm init -y
npm install electron --save-dev

修改 package.json

{
  "name": "markdown-editor",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  },
  "devDependencies": {
    "electron": "36.1.0",
    "electron-builder": "26.0.12"
  },
  "build": {
    "appId": "com.example.markdowneditor",
    "win": {
      "target": "nsis",
      "icon": "icons/icon.ico",
      "compression": "maximum",
      "asar": true,
      "files": [
        "!**/node_modules/electron-*",
        "!**/node_modules/*/{test,example,doc}", 
        "!**/*.{map,ts,md}"
      ]
    }
  }
}

安装 electron-builder 并打包

npm install electron-builder --save-dev
npm run dist

打包完成后,安装程序会在 dist 文件夹中生成。

由于npm install 安装 Electron 时卡住,使用 Yarn 替代 npm

npm install -g yarn
yarn config set registry https://registry.npmmirror.com
yarn

最后执行:
npm run dist
得到exe安装包,82M,安装后,目录288M。

为什么 Electron 应用体积大?

预览:markdown编辑器

文章标签: web

上一篇 : 使用 Tauri (轻量级替代方案)打包编辑器
下一篇 : 用ds生成markdown编辑器
留言
阅读进度 0%