# mm Com 公共组件开发指南

## 规则（Rules）

- Com 组件位于项目根目录的 `com/` 下，`com/{组件名}/index.js`
- 组件导出 `module.exports` 对象，供其他模块 `require` 使用
- 组件应保持功能单一，避免与业务逻辑耦合
- 全局工具函数可扩展到 `$.utils` 对象上，供所有模块通过 `$.utils.xxx()` 调用

## 方法（Methods）

### 步骤1：创建组件目录和文件

```
com/myhelper/
└── index.js
```

### 步骤2：编写组件代码

```javascript
// com/myhelper/index.js
module.exports = {
    formatDate(timestamp) {
        var d = new Date(timestamp);
        return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    },

    isEmail(str) {
        return /^[\w.-]+@[\w.-]+\.\w+$/.test(str);
    }
};
```

### 步骤3：加载组件

在需要使用的模块中 require：

```javascript
var myhelper = require('./com/myhelper/index.js');
myhelper.formatDate(Date.now());
```

### 步骤4：注册为全局工具（可选）

在 App 的 `_init` 或 sys 的 `com/index.js` 中注册为全局函数：

```javascript
if (!$.utils) { $.utils = {}; }
$.utils.formatDate = function(ts) {
    var d = new Date(ts);
    return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
};
// 全局调用：$.utils.formatDate(Date.now())
```

## 技巧（Tips）

- 组件路径用相对路径，相对于调用文件的位置
- 全局工具通过 `$.` 前缀访问，适合频繁调用的工具函数
- 应用层面的公共组件放在 `com/` 下，框架层面的组件放在 `mm_os` 包中
- 参考实现：`com/` 目录下已有组件示例
