我的electron教程系列
electron教程(一): electron的安裝和項目的創建
electron教程(番外篇一): 開發環境及插件, VSCode調試, ESLint + Google JavaScript Style Guide代碼規范
electron教程(番外篇二): 使用TypeScript版本的electron, VSCode調試TypeScript, TS版本的ESLint
electron教程(二): http服務器, ws服務器, 子進程管理
electron教程(三): 使用ffi-napi引入C++的dll
electron教程(四): 使用electron-builder或electron-packager將項目打包為可執行桌面程序(.exe)
引言
這一篇將介紹:
1. 如何將electron替換為TypeScript
.
2. 如何使用VSCode調試TypeScript
.
3. 如何使用ESLint
插件來檢查TypeScript
代碼.
注: TS
是TypeScript
的簡稱, 在本文中, 這兩個名字的所指代的內容完全相同.
TS版本electron
1. 部署node.js+electron環境
按步驟完成electron教程(一): electron的安裝和項目的創建所介紹的內容.
2. 安裝TypeScript
在項目根目錄, 執行指令:
npm install typescript -g
之后執行指令:
npm install @types/node --save-dev
此時TS就已經安裝完成了
3. 創建TypeScript編譯用配置文件
首先要知道,純粹的TS源碼是不能運行和調試的。
當我們要運行TS源碼時,其實是利用TS源碼生成了對應的JS源碼, 以及一個sourcemap
文件, 該文件保存着位置信息, 也就是轉換后的JS代碼的每一個位置, 所對應的轉換前的TS位置.
將.ts
文件轉換為.js
文件所用的命令是tsc
, 這條命令源自我們剛才安裝的TypeScript編譯器(npm install typescript -g
).
例如在hello.ts
文件所在的目錄執行如下命令后:
tsc hello.ts
一旦編譯成功,就會在相同目錄下生成hello.js
和hello.js.map
文件.
你也可以通過命令參數/修改配置文件來修改默認的輸出名稱和目錄等.
現在我們通過修改配置文件來對tsc
編譯進行配置.
在項目根目錄下, 創建tsconfig.json
配置文件, 內容如下:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2019",
"noImplicitAny": false, // 在表達式和聲明上有隱含的'any'類型時報錯, 最好之后改成true
"sourceMap": true,
"outDir": "./dist", // 輸出目錄
"baseUrl": ".",
"paths": {
"*": ["node_modules/*"]
}
},
"include": [
"src/**/*"
]
}
可以看到這里指定了dist目錄
為輸出目錄
, 而來源是src目錄
,
它指明了: 將src目錄
下所有.ts
文件, 編譯為.js
文件, 並且將.js
文件, 放置在dist目錄
中, 其二級目錄和多級目錄, 和src目錄
保持一致.
4. 修改package.json, 添加src命令
修改package.json
文件中的script
腳本, 如下:
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"start": "npm run build && electron ./dist/main.js"
},
可以看到, 主要修改有3處:
-
添加
build
腳本, 內容為"tsc"
.
即在當前目錄運行tsc
命令, 而tsc
命令會依據剛才創建的tsconfig.json
配置文件進行編譯. -
添加了
watch
腳本, 用於 // todo -
修改
start
腳本.
腳本內容分為兩段, 用&&
隔開.
第一段為在當前命令執行npm run build
指令, 也就是運行build
腳本.
第二段為electron ./dist/main.js
, 即用electron
啟動dist
目錄下的main.js
文件. 注意此時main.js
文件位於dist
目錄, 因為該文件是tsc
自動生成的, 生成在了dist
目錄中.
5. 創建preload.ts文件
在項目的src目錄下, 創建preload.ts
, 內容如下:
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener("DOMContentLoaded", () => {
const replaceText = (selector: string, text: string) => {
const element = document.getElementById(selector);
if (element) {
element.innerText = text;
}
};
for (const type of ["chrome", "node", "electron"]) {
replaceText(`${type}-version`, (process.versions as any)[type]);
}
});
6. 創建main.ts文件
此時, 我們刪除步驟1中在src目錄
下創建的main.js
, 我們不再需要這個.js
文件, 取而代之的是, main.ts
文件, 內容如下:
import {app, BrowserWindow} from 'electron';
import * as path from 'path';
let mainWindow: Electron.BrowserWindow;
/**
*
*/
function createWindow(): void {
// Create the browser window.
mainWindow = new BrowserWindow({
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
},
width: 800,
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, '../html/index.html'));
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.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.
mainWindow = 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 OS X 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 OS X 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 (mainWindow === 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.
7. 運行electron
此時, 我們已經完成了對electron的升級, TS
版electron已經完工.
執行指令:
npm start
如果編譯通過, 就會在dist目錄
下生成正確的main.js
文件, main.js.map
文件, preload.js
文件和preload.js.map
文件.
緊接着, electron程序自動啟動.
使用VSCode調試TypeScript
1. 配置VSCode調試JavaScript
按步驟完成使用VSCode調試啟動項目所介紹的內容.
2. 增加TypeScript配置
修改.vscode
目錄下的launch.json
配置文件.
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Electron JS", // 配置方案名字, 左下角可以選
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"program": "${workspaceFolder}/src/mainJS.js", // electron入口
"protocol": "inspector" // 默認的協議是legacy,該協議導致不進入斷點
},
{
"type": "node",
"request": "launch",
"name": "Electron TS", // 配置方案名字, 左下角可以選
"program": "${workspaceFolder}/dist/main.js", // 這里要寫編譯后的js文件, 即electron入口
"preLaunchTask": "tsc: build - tsconfig.json",
"sourceMaps": true, // 必須為true
"outFiles": ["${workspaceFolder}/**/*.js"],
"runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
"protocol": "inspector" // 默認的協議是legacy,該協議導致不進入斷點
}
]
}
我們在原來的基礎上, 增加了TypeScript的調試配置方案, 取名為Electron TS
.
3. 啟用TypeScript配置
重新啟動VSCode, 保證已經將項目目錄復制到了VSCode工作區.
按照如下步驟, 啟用ELectron TS
配置方案.
此時, VSCode會自動啟動調試(F5). 如果你事先打了斷點, 將進入斷點, 如果沒有打斷點, 會直接啟動electron程序.
使用ESLint
插件來檢查TypeScript代碼
1. 部署node.js+electron環境
按步驟完成安裝ESLint代碼檢查工具, Google JavaScript Style Guide所介紹的內容.
2. 安裝TypeScript的ESLint依賴
執行指令:
yarn add @typescript-eslint/parser --save-dev
執行指令:
yarn add @typescript-eslint/eslint-plugin --save-dev
3. 修改VSCode配置文件setting.json
通過快捷鍵cmd + shift + P
打開搜索, 輸入setting
, 按照圖中所示, 選中首選項: 打開設置
:
在setting.json
中, 添加如下內容:
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "typescript",
"autoFix": true
}
]
4. 修改ESLint配置文件.eslintrc.js
將.eslintrc.js
修改`為如下內容:
module.exports = {
"extends": ["google", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"parserOptions": {
"ecmaVersion": 2018
},
"env": {
"es6": true
},
rules: {
"no-console": "off",
"@typescript-eslint/indent": ["error", 2],
"linebreak-style": ["error","windows"],
}
};
5. 重啟VSCode
重啟后, ESLint生效.