宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

我的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处:

添加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.getElementByIdselector);
    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'),
    },
     800,
  });
  // and load the index.html of the app.
  mainWindow.loadFilepath.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生效.