# ESM 与 CJS

Canonical URL: https://developers.iagenify.com/zh/sdk/esm-and-cjs/
Language: zh

软件包包是 ESM. A . A . A CommonJS 需要是建构的,是捆绑的,而不是转寄的复制件——这就是为什么在改变来源后,一种习惯很重要。

Status: type: module · 双入口 · 无运行时依赖

## 入境点 {#map}

```javascript
{
  "type": "module",
  "main": "./dist/index.cjs",
  "exports": {
    ".": {
      "import": "./src/index.js",     // ESM gets the source
      "require": "./dist/index.cjs"   // CJS gets the bundle
    }
  },
  "engines": { "node": ">=18" }
}
```

`import` 读取发布源, 所以在软件包中真实文件的堆叠跟踪点 。 `require` 读取一个预组合的文件 。

## Node 内建内建内建外部 {#builtins}

入境点内线 `node:fs`, `node:os`, `node:path`, `node:crypto` 或 `node:child_process`。它们是在运行时在检查后进口的,检查后,在不存在它们的地方,就让相同的文件负载(即:导入完全失败和 SDK 使用该运行时的后退 。

实际后果在于你的捆包配置,而不是代码——见 [安安装](/zh/sdk/install#bundlers).

## 混合两者 {#interop}

a 中 CommonJS 对象。在 ESM 名为导入文件, 命名的导入文件直接工作。 两者都给相同的类, 所以 `instanceof` 持有——只要一个过程装载其中之一,而不是两者兼有。

```javascript
// CommonJS
const { IaGenify, NotEnoughCredits } = require("iagenify");

// CommonJS reaching for the ESM entry point, when you need it
const { IaGenify } = await import("iagenify");
```

> **不同时在一个进程装入两个**
>
> 被 ESM 复制不是 CJS 复制的类。 错误仍然包含名称、 状态和代码, 所以如果您无法避免混和, 请测试这些 。

## 类型类型 {#typescript}

包装船舶没有类型声明。 `moduleResolution: "bundler"` 或 `"node16"` 导入分辨率; 形状未打字。

```javascript
// iagenify.d.ts — enough to stop the compiler complaining
declare module "iagenify" {
  export class IaGenify {
    constructor(options: {
      apiKey?: string; baseUrl?: string; storage?: unknown;
      sessionPath?: string; appName?: string; timeout?: number;
    });
    [key: string]: any;
  }
  export class IaGenifyError extends Error { status: number; code: string; details?: unknown }
  export class Unauthorized extends IaGenifyError {}
  export class NotEnoughCredits extends IaGenifyError { required: number; available: number }
}
```

```python
# Python has no ESM/CommonJS split: one package, one import path.
# Your own pyproject.toml only declares the dependency:
#
# [project]
# name = "my-app"
# requires-python = ">=3.10"
# dependencies = ["iagenify>=0.1.0"]
from iagenify import IaGenify
```

```python
# Python has one import statement for every kind of script
from iagenify import IaGenify, NotEnoughCredits

# Importing lazily, when you need it
import importlib
iagenify = importlib.import_module("iagenify")
```

```python
# Type checkers read the package's Python signatures directly:
# no separate declaration file is needed.
from iagenify import IaGenify, IaGenifyError, Unauthorized, NotEnoughCredits

api: IaGenify = IaGenify(api_key=api_key, base_url=None, session_path=None, app_name=None, timeout=60)

try:
    api.get_user()
except NotEnoughCredits as error:      # error.required, error.available
    ...
except IaGenifyError as error:         # error.status, error.code, error.details
    ...
```
