模块链接

模块链接(Module Link)是 Esmx 提供的一种微服务架构下的代码共享机制。它支持在不同的独立服务之间:

  • 共享组件和工具函数
  • 统一管理第三方依赖的版本
  • 支持不同环境的特定实现

快速开始

以在微服务架构中共享 Vue 框架为例:

  1. 在提供服务中导出 Vue
1// service-shared/entry.node.ts
2export default {
3    modules: {
4        exports: ['npm:vue']
5    }
6}
  1. 在使用服务中导入
1// service-app/entry.node.ts
2export default {
3    modules: {
4        links: {
5            'shared': '../service-shared/dist'    // 指向共享服务的构建目录
6        },
7        imports: {
8            'vue': 'shared/vue'                   // 从共享服务导入 Vue
9        }
10    }
11}
  1. 在代码中使用
1import { createApp } from 'vue';        // 自动使用共享服务提供的 Vue 版本

基本概念

模块链接涉及两个主要角色:

提供服务

作为共享能力的提供方,负责导出公共依赖、组件和工具函数:

1// service-shared/entry.node.ts
2export default {
3    modules: {
4        exports: [
5            'npm:vue',                         // 共享 npm 包
6            'root:src/components/button.vue',  // 共享组件
7            {
8                'api': {                       // 环境特定实现
9                    inputTarget: {
10                        client: './src/api.browser.ts',
11                        server: './src/api.node.ts'
12                    }
13                }
14            }
15        ]
16    }
17}

使用服务

作为能力的使用方,通过模块链接机制使用其他服务提供的代码:

1// service-app/entry.node.ts
2export default {
3    modules: {
4        // 1. 声明依赖的服务
5        links: {
6            'shared': '../service-shared/dist'
7        },
8
9        // 2. 配置要使用的功能
10        imports: {
11            'vue': 'shared/vue',                    // 使用共享的 Vue
12            'button': 'shared/components/button',    // 使用共享组件
13            'api': 'shared/api'                     // 使用共享 API
14        }
15    }
16}

导出规则

服务间共享支持三种方式:

1. npm 包

用于在服务间统一第三方依赖的版本:

1// 导出 npm 包
2'npm:vue'           // Vue 框架
3'npm:axios'         // HTTP 客户端

2. 服务内组件

用于共享服务内部开发的组件和工具:

1// 导出源码文件(需要带扩展名)
2'root:src/components/button.vue'    // Vue 组件
3'root:src/utils/format.ts'         // 工具函数

3. 环境适配

用于提供不同环境下的特定实现:

1{
2    'api': {
3        inputTarget: {
4            client: './src/api.browser.ts',    // 使用浏览器 API
5            server: './src/api.node.ts'        // 使用 Node.js API
6        }
7    }
8}

参考示例

你可以参考以下完整示例: