SDK 介绍

随着 AIP 开发能力的逐渐完善,开发者迫切需要一种可以支持 AIP 代码组织和共享的方式,参考 Vue/React 等社区主流框架的设计思路,提出多组件复用规范。为此,我们定义了一种新的 AIP 使用方式——SFC,提供类似 Vue SFCopen in new window 的接口和使用方式,提供引入其他 HTML/JS/CSS 文件的能力,使开发者尽可能复用组件、函数和样式,提升开发效率,同时也为后期社区生态的建立提供基础。

使用了 SFC 进行 AIP 页面的编写后,如下图所示,开发者可以将离散的 AIP 页面通过多种相互关连的 SFC 组件封装的方式串联组织起来。

为什么使用 SFC

  • 开发者可以使用熟悉的 HTML、CSS 和 JavaScript 分模块进行组件的封装
  • 组件和代码逻辑可抽象并复用
  • 更好的 IDE 支持,AIP 提供了对应的VS Code 插件open in new window
  • 预编译模板

开始使用

SDK 安装

环境

推荐 Node.js 版本:16.14.0(LTS)

步骤

  1. 切换到项目目录下,需包含 package.json
  2. 下载 shell 脚本到本地
   curl https://unpkg.byted-static.com/latest/byted-fangyuan/aip-sfc-transformer/dist/sfc-installer -O
1
  1. 在项目目录下运行该脚本:bash ./sfc-installer,产物包括:

    产物说明
    ./components.json组件映射表
    ./aip-sfc-transformer.cjs.js核心执行库
    node_modules以下外部依赖会安装在 node_modules 中:
    esbuild@0.14.9
    lodash@4.17.21
    uuid@8.3.2
    sass@1.49.7

SDK 使用方式

提供入口函数:transformSFC

入口函数类型定义

/**
 * entryFile: 入口文件,必须为 .aip 文件
 * options: 配置参数
 * props: 传入 entryFile 模版的默认 state
 */
type TransformSFC = (
    entryFile: string,
    options: Options,
    props: TransformProps = {},
) => string;

// 配置
interface Options {
    // 生成结果,template 表示模版片段,html 表示完整 aip 结果,默认 html
    target: 'template' | 'html';
    // html 标题,仅在 target 为 html 时生效
    title?: string;
    // 全局组件注入
    globalComponents?: DepMap;
}

// props 可使用类型
type SimpleType = string | Array<SimpleType> | { [key: string]: SimpleType } | number | boolean | null;
type TransformProps = Record<string, SimpleType>;

/**
 * 全局组件依赖关系映射
 * key:组件名,必须为 Pascal 形式,如 CustomComponent
 * `filePath`:文件路径
 * `rawContent`:文件内容,当传入文件内容时不读取文件路径文本,同时也支持传入 filePath 在文本内容中引入其他相对路径组件
 */
type DepMap = Record<
    string,
    {
        filePath?: string;
        rawContent?: string;
    }
>;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

配置说明

  • 配置中的 target字段的作用:
    • template
      • 所有的 SFC 样式均视为 scoped 样式,仅会在关联的类名和 id 上内联匹配的样式
    • html
      • SFC 声明的样式如果包含 scoped 属性,与 template 行为一致
      • SFC 声明的样式未包含 scoped 属性,自动在生成结果中新增 aip-custom style 并放置样式到其中
      • 若入口文件没有 head 标签,自动添加 head 标签和组件引用 script
  • props 选项
    • 传入模版的属性,支持上方描述的SimpleType内定义的这几种基本类型
    • 最终会将 props 属性放置到 state 中,如有同名属性,则默认会被 props 替换
  • globalComponents 选项
    • 用于从外部注入全局的自定义组件,组件命名必须为 Pascal 形式
    • 详细用法参见此处

SDK 使用示例

const { transformSFC } = require('./aip-sfc-transformer.cjs');
const html = transformSFC(
    './a.aip',
    { target: 'html' },
    {
        className: 'classTest',
        showBtn: 'true',
    },
);
console.log(html); // aip html 结果
1
2
3
4
5
6
7
8
9
10

更多完整 SFC 样例请参考此处

Last Updated: 2022/7/15 下午7:22:06