electron教程(番外篇二): 使用TypeScript版本的electron, VSCode調試TypeScript, TS版本的ESLint


我的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代碼.

注: TSTypeScript的簡稱, 在本文中, 這兩個名字的所指代的內容完全相同.

 

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.jshello.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處:

  1. 添加build腳本, 內容為"tsc".
    即在當前目錄運行tsc命令, 而tsc命令會依據剛才創建的tsconfig.json配置文件進行編譯.

  2. 添加了watch腳本, 用於 // todo

  3. 修改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生效.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM