1.1 Sciter-JS 概述

什么是 Sciter-JS?

Sciter-JS 是一个革命性的桌面应用开发框架,它将现代 Web 技术与原生桌面应用的性能完美结合。与传统的 Electron 等框架不同,Sciter-JS 提供了更轻量级、更高性能的解决方案。

flowchart TB
    subgraph "传统桌面开发"
        A[C++/C#] --> B[复杂的 UI 框架]
        B --> C[平台特定代码]
    end
    
    subgraph "Web 技术桌面化"
        D[Electron] --> E[Chromium + Node.js]
        E --> F[资源消耗大]
    end
    
    subgraph "Sciter-JS 方案"
        G[HTML/CSS/JS] --> H[Sciter 引擎]
        H --> I[轻量级原生应用]
    end
    
    style I fill:#90EE90
    style F fill:#FFB6C1
    style C fill:#FFE4B5

核心优势

1. 性能优势

  • 启动速度:比 Electron 应用快 3-5 倍
  • 内存占用:仅为 Electron 应用的 110
  • 包体积:运行时仅 8-12MB

2. 开发效率

  • 熟悉的技术栈:HTML、CSS、JavaScript
  • 现代化语法:支持 ES6+、模块化
  • 丰富的 API:系统级功能访问

3. 部署便利

  • 单文件部署:无需安装额外运行时
  • 跨平台支持:Windows、macOS、Linux
  • 自动更新:内置更新机制

技术架构

architecture-beta
    group api(cloud)[API Layer]
    group engine(server)[Sciter Engine]
    group system(disk)[System Layer]
    
    service js(internet)[JavaScript Runtime] in api
    service dom(internet)[DOM API] in api
    service css(internet)[CSS Engine] in api
    
    service render(server)[Rendering Engine] in engine
    service layout(server)[Layout Engine] in engine
    service script(server)[Script Engine] in engine
    
    service os(disk)[OS APIs] in system
    service file(disk)[File System] in system
    service net(disk)[Network] in system

    
    js:B -- T:render
    dom:B -- T:layout
    css:B -- T:layout
    render:B -- T:os
    layout:B -- T:file
    script:B -- T:net

1.2 环境搭建

系统要求

操作系统 最低版本 推荐版本 架构支持
Windows Windows 7 Windows 10+ x64, ARM64
macOS 10.12 11.0+ x64, ARM64
Linux Ubuntu 16.04 Ubuntu 20.04+ x64, ARM64

下载和安装

方法一:官方下载

  1. 访问 Sciter 官网
  2. 选择对应平台的 SDK
  3. 下载并解压到开发目录
# Windows
wget https://sciter.com/sdk/sciter-js-sdk-windows.zip
unzip sciter-js-sdk-windows.zip

# macOS
wget https://sciter.com/sdk/sciter-js-sdk-macos.zip
unzip sciter-js-sdk-macos.zip

# Linux
wget https://sciter.com/sdk/sciter-js-sdk-linux.zip
unzip sciter-js-sdk-linux.zip

方法二:包管理器安装

# npm 安装(推荐)
npm install -g @sciter-js/cli

# yarn 安装
yarn global add @sciter-js/cli

# 验证安装
sciter --version

开发工具配置

VS Code 配置

  1. 安装扩展
// .vscode/extensions.json
{
  "recommendations": [
    "sciter-js.sciter-js",
    "ms-vscode.vscode-typescript-next",
    "bradlc.vscode-tailwindcss",
    "formulahendry.auto-rename-tag"
  ]
}
  1. 工作区配置
// .vscode/settings.json
{
  "sciter.sdk.path": "./sciter-sdk",
  "sciter.debug.enabled": true,
  "files.associations": {
    "*.htm": "html",
    "*.tis": "javascript"
  },
  "emmet.includeLanguages": {
    "tis": "javascript"
  }
}
  1. 调试配置
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Sciter App",
      "type": "sciter",
      "request": "launch",
      "program": "${workspaceFolder}/main.htm",
      "args": ["--debug"]
    }
  ]
}

其他编辑器配置

Sublime Text

// Sciter.sublime-syntax
{
  "name": "Sciter",
  "file_extensions": ["tis"],
  "scope": "source.js",
  "extends": "Packages/JavaScript/JavaScript.sublime-syntax"
}

WebStorm/IntelliJ

<!-- sciter-file-types.xml -->
<component name="FileTypeManager" version="17">
  <extensionMap>
    <mapping ext="tis" type="JavaScript" />
  </extensionMap>
</component>

1.3 第一个 Hello World 应用

项目结构

hello-world/
├── main.htm          # 主页面文件
├── main.js           # 主脚本文件
├── style.css         # 样式文件
├── package.json      # 项目配置
└── sciter.exe        # 运行时(Windows)

创建项目

1. 初始化项目

# 创建项目目录
mkdir hello-world
cd hello-world

# 初始化 package.json
npm init -y

# 安装 Sciter CLI
npm install @sciter-js/cli --save-dev

2. 创建主页面文件

<!-- main.htm -->
<!DOCTYPE html>
<html>
<head>
    <title>Hello Sciter-JS</title>
    <meta charset="utf-8">
    <style src="style.css"></style>
    <script type="module" src="main.js"></script>
</head>
<body>
    <div class="container">
        <h1 id="title">Hello, Sciter-JS!</h1>
        <p class="description">
            这是您的第一个 Sciter-JS 应用程序
        </p>
        <div class="button-group">
            <button id="btn-hello" class="btn btn-primary">
                点击问候
            </button>
            <button id="btn-info" class="btn btn-secondary">
                系统信息
            </button>
        </div>
        <div id="output" class="output"></div>
    </div>
</body>
</html>

3. 创建样式文件

/* style.css */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.container {
    background: white;
    padding: 2rem;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    text-align: center;
    max-width: 400px;
    width: 90%;
}

#title {
    color: #333;
    margin-bottom: 1rem;
    font-size: 2rem;
    font-weight: 600;
}

.description {
    color: #666;
    margin-bottom: 2rem;
    line-height: 1.5;
}

.button-group {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
    justify-content: center;
}

.btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 6px;
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-primary {
    background: #667eea;
    color: white;
}

.btn-primary:hover {
    background: #5a6fd8;
    transform: translateY(-1px);
}

.btn-secondary {
    background: #f8f9fa;
    color: #495057;
    border: 1px solid #dee2e6;
}

.btn-secondary:hover {
    background: #e9ecef;
    transform: translateY(-1px);
}

.output {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 1rem;
    min-height: 60px;
    text-align: left;
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    color: #495057;
    white-space: pre-wrap;
}

.output:empty::before {
    content: "输出将显示在这里...";
    color: #adb5bd;
    font-style: italic;
}

/* 动画效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.container {
    animation: fadeIn 0.5s ease-out;
}

4. 创建主脚本文件

// main.js
import * as sys from "@sys";
import * as env from "@env";

// 应用程序类
class HelloWorldApp {
    constructor() {
        this.initializeElements();
        this.bindEvents();
        this.showWelcomeMessage();
    }

    // 初始化 DOM 元素引用
    initializeElements() {
        this.titleElement = document.querySelector('#title');
        this.outputElement = document.querySelector('#output');
        this.helloButton = document.querySelector('#btn-hello');
        this.infoButton = document.querySelector('#btn-info');
    }

    // 绑定事件处理器
    bindEvents() {
        this.helloButton.addEventListener('click', () => this.showGreeting());
        this.infoButton.addEventListener('click', () => this.showSystemInfo());
        
        // 键盘快捷键
        document.addEventListener('keydown', (event) => {
            if (event.ctrlKey && event.key === 'h') {
                this.showGreeting();
            } else if (event.ctrlKey && event.key === 'i') {
                this.showSystemInfo();
            }
        });
    }

    // 显示欢迎消息
    showWelcomeMessage() {
        this.updateOutput('欢迎使用 Sciter-JS!\n\n快捷键:\nCtrl+H - 问候\nCtrl+I - 系统信息');
    }

    // 显示问候消息
    showGreeting() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('zh-CN');
        const greetings = [
            '你好,世界!',
            'Hello, World!',
            'Bonjour le monde!',
            'Hola, Mundo!',
            'こんにちは、世界!'
        ];
        
        const randomGreeting = greetings[Math.floor(Math.random() * greetings.length)];
        
        this.updateOutput(`${randomGreeting}\n\n当前时间: ${timeString}\n点击次数: ${this.getClickCount()}`);
        this.incrementClickCount();
        
        // 添加视觉反馈
        this.titleElement.style.color = this.getRandomColor();
    }

    // 显示系统信息
    showSystemInfo() {
        try {
            const systemInfo = {
                '操作系统': env.PLATFORM,
                '架构': env.ARCH || 'unknown',
                '用户名': env.USERNAME || env.USER || 'unknown',
                '主目录': env.HOME || env.USERPROFILE || 'unknown',
                '当前目录': env.cwd(),
                'Sciter 版本': env.sciterVersion(),
                '内存使用': this.formatBytes(sys.memoryUsage().rss)
            };

            let output = '=== 系统信息 ===\n\n';
            for (const [key, value] of Object.entries(systemInfo)) {
                output += `${key}: ${value}\n`;
            }
            
            this.updateOutput(output);
        } catch (error) {
            this.updateOutput(`获取系统信息时出错: ${error.message}`);
        }
    }

    // 更新输出区域
    updateOutput(text) {
        this.outputElement.textContent = text;
        this.outputElement.scrollTop = this.outputElement.scrollHeight;
    }

    // 获取点击次数
    getClickCount() {
        return parseInt(localStorage.getItem('clickCount') || '0');
    }

    // 增加点击次数
    incrementClickCount() {
        const count = this.getClickCount() + 1;
        localStorage.setItem('clickCount', count.toString());
    }

    // 获取随机颜色
    getRandomColor() {
        const colors = ['#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe', '#00f2fe'];
        return colors[Math.floor(Math.random() * colors.length)];
    }

    // 格式化字节数
    formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
}

// 应用程序入口点
document.addEventListener('DOMContentLoaded', () => {
    new HelloWorldApp();
});

// 窗口关闭确认
window.addEventListener('beforeunload', (event) => {
    const clickCount = parseInt(localStorage.getItem('clickCount') || '0');
    if (clickCount > 0) {
        event.returnValue = '确定要关闭应用程序吗?';
        return '确定要关闭应用程序吗?';
    }
});

// 导出应用程序类(用于测试)
export { HelloWorldApp };

5. 配置项目文件

// package.json
{
  "name": "hello-world-sciter",
  "version": "1.0.0",
  "description": "第一个 Sciter-JS 应用程序",
  "main": "main.htm",
  "scripts": {
    "start": "sciter main.htm",
    "dev": "sciter main.htm --debug",
    "build": "sciter-packager --input main.htm --output dist/",
    "test": "sciter main.htm --test"
  },
  "keywords": ["sciter", "desktop", "app"],
  "author": "Your Name",
  "license": "MIT",
  "devDependencies": {
    "@sciter-js/cli": "^1.0.0"
  },
  "sciter": {
    "window": {
      "title": "Hello Sciter-JS",
      "width": 500,
      "height": 400,
      "resizable": true,
      "minimizable": true,
      "maximizable": true
    },
    "debug": true
  }
}

运行应用程序

开发模式运行

# 方法一:使用 npm 脚本
npm run dev

# 方法二:直接使用 sciter 命令
sciter main.htm --debug

# 方法三:使用 SDK 中的可执行文件
./sciter-sdk/bin/sciter main.htm

生产模式运行

# 正常运行
npm start

# 或者
sciter main.htm

1.4 开发工具介绍

Sciter Inspector

Sciter Inspector 是内置的开发者工具,类似于浏览器的开发者工具。

启用 Inspector

// 在代码中启用
import * as sys from "@sys";

// 开启调试模式
sys.debug = true;

// 显示 Inspector
sys.inspector();

快捷键

快捷键 功能
F12 打开/关闭 Inspector
Ctrl+Shift+I 打开 Inspector
Ctrl+R 重新加载页面
Ctrl+Shift+R 强制重新加载

Inspector 功能

  1. 元素检查器

    • DOM 树查看
    • 样式实时编辑
    • 计算样式查看
  2. 控制台

    • JavaScript 执行
    • 错误日志查看
    • 性能分析
  3. 网络监控

    • 资源加载监控
    • 请求响应查看
    • 性能分析

调试技巧

1. 日志输出

// 基本日志
console.log('调试信息');
console.warn('警告信息');
console.error('错误信息');

// 格式化输出
console.log('用户: %s, 年龄: %d', 'Alice', 25);

// 对象输出
console.dir(document.body);

// 性能测试
console.time('操作耗时');
// ... 执行代码
console.timeEnd('操作耗时');

2. 断点调试

// 代码断点
debugger;

// 条件断点
if (condition) {
    debugger;
}

// 异常断点
try {
    // 可能出错的代码
} catch (error) {
    debugger;
    console.error(error);
}

3. 性能分析

// 性能标记
performance.mark('start');
// ... 执行代码
performance.mark('end');
performance.measure('操作耗时', 'start', 'end');

// 内存使用
import * as sys from "@sys";
console.log('内存使用:', sys.memoryUsage());

常用开发插件

VS Code 扩展

  1. Sciter-JS Language Support

    • 语法高亮
    • 代码补全
    • 错误检查
  2. Sciter Debugger

    • 断点调试
    • 变量查看
    • 调用栈分析
  3. HTML CSS Support

    • HTML/CSS 智能提示
    • 标签自动闭合
    • 格式化支持

浏览器扩展

  1. Sciter DevTools
    • 远程调试
    • 实时预览
    • 性能监控

1.5 项目配置详解

窗口配置

// package.json 中的 sciter 配置
{
  "sciter": {
    "window": {
      "title": "应用标题",
      "width": 800,
      "height": 600,
      "minWidth": 400,
      "minHeight": 300,
      "maxWidth": 1200,
      "maxHeight": 900,
      "resizable": true,
      "minimizable": true,
      "maximizable": true,
      "closable": true,
      "alwaysOnTop": false,
      "center": true,
      "frame": "standard",
      "icon": "icon.ico"
    }
  }
}

应用配置

{
  "sciter": {
    "debug": true,
    "inspector": true,
    "console": true,
    "resources": {
      "archive": "resources.dat",
      "compress": true
    },
    "security": {
      "allowFileAccess": true,
      "allowNetworkAccess": true,
      "allowSystemAccess": false
    }
  }
}

构建配置

// sciter.config.js
module.exports = {
  input: 'main.htm',
  output: 'dist/',
  resources: {
    include: ['assets/**/*', 'data/**/*'],
    exclude: ['**/*.tmp', '**/*.log']
  },
  minify: {
    html: true,
    css: true,
    js: true
  },
  target: {
    platform: ['win32', 'darwin', 'linux'],
    arch: ['x64', 'arm64']
  }
};

1.6 常见问题解决

安装问题

问题:下载速度慢

# 使用国内镜像
npm config set registry https://registry.npmmirror.com
npm install -g @sciter-js/cli

# 或使用 cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install -g @sciter-js/cli

问题:权限错误

# Linux/macOS
sudo npm install -g @sciter-js/cli

# 或配置 npm 全局目录
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH

运行问题

问题:应用无法启动

  1. 检查文件路径 “`bash

    确保文件存在

    ls -la main.htm

检查权限

chmod +x sciter


2. **检查语法错误**
```javascript
// 使用 try-catch 捕获错误
try {
    // 应用代码
} catch (error) {
    console.error('启动错误:', error);
}

问题:样式不生效

  1. 检查文件引用 html <!-- 确保路径正确 --> <style src="./style.css"></style> 2. 检查 CSS 语法 css /* 使用浏览器开发者工具验证 CSS */

调试问题

问题:Inspector 无法打开

// 确保启用调试模式
import * as sys from "@sys";
sys.debug = true;

// 手动打开 Inspector
sys.inspector();

问题:断点不生效

// 确保在调试模式下运行
// 使用 console.log 替代断点
console.log('调试点:', variable);

1.7 本章小结

学习成果

通过本章学习,您已经:

  1. ✅ 了解了 Sciter-JS 的核心概念和优势
  2. ✅ 完成了开发环境的搭建和配置
  3. ✅ 创建并运行了第一个 Hello World 应用
  4. ✅ 掌握了基本的调试技巧和工具使用
  5. ✅ 学会了项目配置和常见问题解决

核心要点

概念 重要性 应用场景
Sciter-JS 架构 ⭐⭐⭐⭐⭐ 理解框架原理
环境搭建 ⭐⭐⭐⭐⭐ 开发基础
项目结构 ⭐⭐⭐⭐ 代码组织
调试工具 ⭐⭐⭐⭐ 问题排查
配置管理 ⭐⭐⭐ 应用定制

最佳实践

  1. 项目组织

    • 使用清晰的目录结构
    • 分离 HTML、CSS、JavaScript
    • 合理命名文件和变量
  2. 开发流程

    • 始终在调试模式下开发
    • 及时测试和验证功能
    • 使用版本控制管理代码
  3. 性能考虑

    • 避免不必要的资源加载
    • 优化图片和静态资源
    • 合理使用缓存机制

下一步学习

在下一章中,我们将深入学习:

  • Sciter-JS 语法特性:了解与标准 JavaScript 的差异
  • DOM 操作技巧:掌握高效的元素操作方法
  • 选择器和查询:学习强大的元素选择功能
  • 属性和样式操作:实现动态界面效果

练习建议

  1. 基础练习

    • 修改 Hello World 应用的样式
    • 添加更多交互功能
    • 尝试不同的窗口配置
  2. 进阶练习

    • 创建一个简单的计算器
    • 实现一个待办事项列表
    • 制作一个系统信息查看器
  3. 探索练习

    • 研究官方示例代码
    • 尝试集成第三方库
    • 实验不同的布局方案

恭喜您完成了第一章的学习! 🎉

现在您已经具备了 Sciter-JS 开发的基础知识,可以开始创建更复杂的桌面应用程序了。记住,实践是最好的学习方式,多动手编写代码,多尝试不同的功能,您会很快掌握 Sciter-JS 的精髓。