###### tags: `Node.js`
# Electron 包裝
首先安裝Electron
```jsx=
npm install electron --save
```
建立main.js
主要控制electron的視窗函式
以下為官方提供
可將其內的code放於其他js檔內,以可調用為主**
##### main.js
```javascript=
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: 800, height: 600})
// 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
接下來設定package.json
##### package.json
```json=
{
"name": "watching",
"version": "1.0.0",
"description": "watching product.",
"main": "api.js",
"scripts": {
"start": "electron .",
"bulid_win":"electron-packager . WinApp --platform=win32 --arch=x64"
},
```
此例中
我將官方提供的main.js的程式碼放入api.js,以便能同時開啟sever,這應該不是最好的辦法啦
第5行的main設定引用有官方程式碼的檔案
第7行是使用electron啟動專案
第8行是將專案輸出成.exe檔
指令為
```jsx=
npm run build_win
```

# 示範

# Tip
1.若要不顯示開發者視窗
將此行註解
```javascript=
win.webContents.openDevTools();
```
2.隱藏主選單列
在 createWindow方法內加入
```javascript=
electron.Menu.setApplicationMenu(null);
```
3.若希望隱藏程式碼,可以在輸出時加入 --asar ,讓electron封裝起來
將bulid_win改成下列
```json=
"build_win": "electron-packager . WinApp --platform=win32 --arch=x64 --asar"
```
4.其餘版本的輸出指令
Linux
```json=
"bulid_linux":"electron-packager . LinuxApp --platform=linux --arch=x64 --asar"
```
Linux ARM
```json=
"bulid_arm":"electron-packager . ARMApp --platform=linux --arch=armv7l --asar"
```
# Dark Theme CSS
{%hackmd theme-dark %}