求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Modeler   Code  
会员   
要资料
 
追随技术信仰

随时听讲座
每天看新闻
 
 
我的electron教程系列
1. electron的安装和项目的创建
2. http服务器, ws服务器, 子进程管理
3. 使用ffi-napi引入C++的dll
4. 使用electron-builder或electron......
5. 开发环境及插件, VSCode调试, ESLint .
6. 使用TypeScript版本的electron......
 

 
 
目录
使用TypeScript版本的electron, VSCode调试TypeScript, TS版本的ESLint
来源:博客园,作者:Silenzio
83 次浏览
2次  

引言

这一篇将介绍:

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

  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生效.


您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码: 验证码,看不清楚?请点击刷新验证码 必填



83 次浏览
2次