本文將帶領大家使用vue-cli + electron-builder構建一個Hello World
Electron是一個基於Chromium和 Node.js,可以使用 HTML、CSS和JavaScript構建跨平台應用的技術框架,兼容 Mac、Windows 和 Linux。
在開始搭建項目之前,需要安裝以下工具
- node.js
1 創建項目
1.1 安裝vue-cli
先查看是否已經安裝了vue-cli,vue-cli的版本是什么
vue -V
如果版本叫老,可以直接卸載,再安裝最新版本
卸載
npm uninstall vue-cli -g
安裝
install @vue/cli -g
1.2 使用vue-cli創建項目
選取一個項目存放的路徑,然后開始創建項目
例如:
vue create electron-vue-helloworld
這里將項目名定為:electron-vue-helloworld
輸入完上述命令之后進入vue項目的創建過程。出現以下內容
Vue CLI v3.8.4
? Please pick a preset: (Use arrow keys)
default (babel, eslint)
> Manually select features
第一個選項是 “default” 默認,只包含babel和eslint
第二個選項是 “Manually select features”自定義安裝
選擇自定義安裝,進入下一步選擇
? Check the features needed for your project: (Press <space> to select, <a> to t
oggle all, <i> to invert selection)
❯◉ Babel
◯ TypeScript
◯ Progressive Web App (PWA) Support
◉ Router
◉ Vuex
◉ CSS Pre-processors
◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
這里我們選擇
- babel(高級的語法轉換為 低級的語法)
- Router(路由)
- Vuex(狀態管理器)
- CSS Pre-processors(css預處理器)
- Linter / Formatter(代碼風格、格式校驗)
然后進入下一步
? Use history mode for router? (Requires proper server setup for index fallback
in production) (Y/n) n
這一步是設置router是否使用history模式,這里我們選n,接着進入下一步
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported
by default): (Use arrow keys)
Sass/SCSS (with dart-sass)
Sass/SCSS (with node-sass)
Less
❯ Stylus
這里是設置css預處理模塊,在這里我要強調一下,不需要亂選,選擇我們熟悉的一種,在這里我們選擇 Stylus ,然后進入下一步
? Pick a linter / formatter config: (Use arrow keys)
ESLint with error prevention only
ESLint + Airbnb config
❯ ESLint + Standard config
ESLint + Prettier
這一步是選擇ESLint代碼檢查工具的配置,這里我們選擇標准配置“ESLint + Standard config”,然后進入下一步
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i
> to invert selection)
❯◉ Lint on save
◯ Lint and fix on commit
這一步是選擇什么時候執行ESLint檢查,這里我們選擇保存時檢查“Lint on save”,然后進入下一步
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.?
In dedicated config files
❯ In package.json
這一步是詢問 babel, postcss, eslint這些配置是單獨的配置文件還是放在package.json 文件中,這里我們選擇“In package.json”,然后進入下一步
? Save this as a preset for future projects? (y/N) N
這一步是詢問時候以后創建項目是否也采用同樣的配置,這里我們選N。到目前為止,vue項目是創建完成了,我們等待項目下載依賴包,等項目構建完畢我們開始集成electron
1.3 使用electron-builder集成electron
進入項目根目錄(electron-vue-helloworld),然后執行下列命令:
vue add electron-builder
這個時候會安裝electron-builder的依賴,可能比較耗費時間,請大家耐心等待,安裝完成后會出現以下選型:
? Choose Electron Version (Use arrow keys)
^4.0.0
^5.0.0
❯ ^6.0.0
這一步是選擇Electron的版本,我們這里選擇最新版本6.0.0,等待安裝完成即可。安裝完成后會在src目錄下生成background.js,並在package.json 文件中修main為"main": "background.js"
至此,所有的安裝都已經完成了,接下來我們就可以運行程序看效果了。
1.4 運行程序
執行以下命令,運行程序
npm run electron:serve
在啟動的時候,會啟動很久,並出現以下信息
INFO Launching Electron...
Failed to fetch extension, trying 4 more times
Failed to fetch extension, trying 3 more times
Failed to fetch extension, trying 2 more times
Failed to fetch extension, trying 1 more times
這是在安裝vuejs devtools,由於網絡問題,一直安裝不上。重試5次之后就會自動跳過並且啟動程序。
編譯成功后,會自動彈出一個桌面程序,如下圖所示
下一期我們將詳細的講一下background.js,里邊的一些參數都是干什么用的。
更多內容請關注公眾號(自增程序員)