最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 从Vue到Electron

    正文概述 掘金(发客)   2021-02-09   406

    前言

    本文介绍一种使用vue-cli-plugin-electron-builder(名字太长,以下简称builder),将现有的Vue单页项目迁移到Electron的做法。

    下面将会以著名的Vue Element Admin为例,详细讲述如何把它变成一个双端项目

    选型

    说到Vue迁移到Electron,网上许多资料都是介绍如何使用electron-vue,但经过对比与实践,我选择使用builder,原因如下:

    1. builder的更新维护更及时,而且issues更少,相比之下,electron-vue的更新基本停滞了,问题也更多

    从Vue到Electron

    从Vue到Electron

    1. electron-vue使用的electron版本很旧,而builder使用的electron跟得上官方的步伐
    • electron-vue用的是2.0.4的electron:

    从Vue到Electron

    • builder的electron版本现在是11.2.1:

    从Vue到Electron

    1. electron-vue是一套基于vue-cli2的项目模版,而builder是基于vue-cli3的脚手架插件

    项目实践也证明这个选择比较明智^_^

    迁移步骤

    进入正题

    首先当然是找到你的Vue项目,本文以Vue Element Admin为例,OK,让我们先下载这个项目:

    git clone https://github.com/PanJiaChen/vue-element-admin.git
    

    第二步,安装依赖:

    cd vue-element-admin
    npm i
    

    跑起来看看:

    npm run dev
    

    前两步走完,我们就有了个棒棒的Vue项目:

    从Vue到Electron

    第三步,安装electron项目所需的依赖:

    不多,基本的就4个:

    npm i -D electron@^9.0.0
    npm i -D electron-devtools-installer@^3.1.0
    npm i -D electron-icon-builder@^2.0.1
    npm i -D vue-cli-plugin-electron-builder@~2.0.0-rc.5
    

    安装依赖的时候可能会遇到两类问题:

    1. electron安装十分缓慢,甚至装不上
    2. 证书错误

    第一类问题可以通过设置镜像来解决:

    npm config set registry https://registry.npm.taobao.org/
    npm set electron_mirror https://npm.taobao.org/mirrors/electron/
    npm set ELECTRON_MIRROR https://cdn.npm.taobao.org/dist/electron/
    

    证书错误多见于在公司安装时发生,与公司使用的代理有关,可以通过如下方法解决:

    npm config set strict-ssl false
    // 注意,把https都变成http:
    npm config set registry http://registry.npm.taobao.org/
    npm set electron_mirror http://npm.taobao.org/mirrors/electron/
    npm set ELECTRON_MIRROR http://cdn.npm.taobao.org/dist/electron/
    

    第四步,划分主进程与渲染进程

    如果你使用vue-cli-plugin-electron-builder来创建项目,它默认是将主进程的源文件设置为background.js,与渲染进程的文件同放在src目录下。

    我还是更喜欢electron-webpack的做法:在src下分出两个目录:main和renderer。main放置主进程相关的代码,而renderer放置渲染进程相关的代码。electron-vue也是这么做的。

    OK,我们也在src下分出两个目录:mainrenderer,然后将原来src下的模块都放进renderer中

    在main中创建index.js(主进程代码),填入如下代码:

    import { app, protocol, BrowserWindow } from 'electron'
    import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
    import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
    const isDevelopment = process.env.NODE_ENV !== 'production'
    
    // Scheme must be registered before the app is ready
    protocol.registerSchemesAsPrivileged([
      { scheme: 'app', privileges: { secure: true, standard: true } }
    ])
    
    async function createWindow() {
      // Create the browser window.
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          <% if (spectronSupport) { %>
          // Required for Spectron testing
          enableRemoteModule: true,
          <% } %>
          // Use pluginOptions.nodeIntegration, leave this alone
          // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
          nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
        }
      })
    
      if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
      } else {
        createProtocol('app')
        // Load the index.html when not in development
        win.loadURL('app://./index.html')
      }
    }
    
    // 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
    
    // 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', async () => {
      if (isDevelopment && !process.env.IS_TEST) {
        // Install Vue Devtools
        try {
          await installExtension(VUEJS_DEVTOOLS)
        } catch (e) {
          console.error('Vue Devtools failed to install:', e.toString())
        }
      }
      createWindow()
    })
    
    // Exit cleanly on request from parent process in development mode.
    if (isDevelopment) {
      if (process.platform === 'win32') {
        process.on('message', (data) => {
          if (data === 'graceful-exit') {
            app.quit()
          }
        })
      } else {
        process.on('SIGTERM', () => {
          app.quit()
        })
      }
    }
    

    第五步,配置vue.config.js:

    注意pluginOptions.electronBuilder.mainProcessFile和configureWebpack中的config.entry.app,配置的详情可见:builder和cli,还要特别注意对svg的处理。

    module.exports = {
      pluginOptions: {
        electronBuilder: {
          mainProcessFile: 'src/main/index.js',
          builderOptions: {
            appId: "catpoint.com",
            productName: "Catpoint",
            icon: "./public/icons/icon.ico",
            files: ["**/*", "static/*"],
            asar: true,
            mac: {
              icon: "./public/icon.png",
              target: ["zip", "dmg"],
              category: "com.catpoint-category.utilities"
            },
            win: {
              icon: "./public/icons/icon.ico",
              target: ["zip", "nsis"]
            },
            nsis: {
              oneClick: false,
              allowElevation: true,
              allowToChangeInstallationDirectory: true,
              installerIcon: "./public/icons/icon.ico",
              uninstallerIcon: "./public/icons/icon.ico",
              installerHeaderIcon: "./public/icons/icon.ico",
              createDesktopShortcut: true,
              createStartMenuShortcut: true,
              license: "./LICENSE.txt"
            }
          }
        }
      },
      ...
      configureWebpack: config => {
        config.entry.app = './src/renderer/main.js'
        return {
          name: name,
          resolve: {
            alias: {
              '@': resolve('src/renderer')
            }
          }
        }
      },
      ...
      chainWebpack(config) {
        config.module
          .rule('svg')
          .exclude.add(resolve('src/renderer/icons'))
          .end()
        config.module
          .rule('icons')
          .test(/\.svg$/)
          .include.add(resolve('src/renderer/icons'))
          .end()
          .use('svg-sprite-loader')
          .loader('svg-sprite-loader')
          .options({
            symbolId: 'icon-[name]'
          })
         .end()
      }
    }
    

    第六步,配置脚本命令:

    "scripts": {
        "dev:desktop": "npm run copy && vue-cli-service electron:serve --mode dev",
        "dev:web": "vue-cli-service serve",
        "build:desktop": "npm run build:icon && npm run build:mac && npm run build:win",
        "build:win": "vue-cli-service electron:build --legacy --windows --x64",
        "build:mac": "vue-cli-service electron:build --legacy --macos",
        "build:icon": "electron-icon-builder --input=./public/icon.png --output=public --flatten",
        "build:web": "vue-cli-service build",
        ...
    },
    

    好了,到这里就完成了迁移,并且支持双端的调试和打包,顺利的话,半个小时就好了。运行npm run dev:desktop和npm run dev:web看看效果吧。

    您也可以看看这个:Proton Admin,一个在Vue Element Admin基础上改建而来的Electron项目,在持续改进和增强中。


    起源地下载网 » 从Vue到Electron

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元