# @adobe/helix-shared-config 中文文档

规范地址：https://npmcn.com/package/%40adobe/helix-shared-config/

版本：11\.2\.7
npm 元数据更新时间：2026-10-20T15:54:39.785Z
中文译文更新时间：2026-11-05T20:07:13.343Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40adobe/helix-shared-config
原文对照：https://npmcn.com/package/%40adobe/helix-shared-config/?lang=original
项目主页：https://github.com/adobe/helix-shared#readme
源码仓库：https://github.com/adobe/helix-shared

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：232 kB，48 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：11 个
- 首次发布：2021-04-29T03:02:28.694Z
- 最新版本发布：2026-10-20T15:54:37.986Z
- 近 30 天下载量：32053（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：189（近 12 个月 26 个）

## 中文简介

Helix 项目共享模块 - 配置

## 安装

```sh
npm install @adobe/helix-shared-config
```

也可以使用：`pnpm add @adobe/helix-shared-config`、`yarn add @adobe/helix-shared-config`、`bun add @adobe/helix-shared-config`

## README

# 螺旋共享 - 配置

配置包为管理各种Helix项目配置提供了一组配置类. 这些类处理来自本地目录或远程 GitHub 寄存器的基于 YAML 的配置文件的加载,校验和管理.

## 安装

```bash
npm install @adobe/helix-shared-config
```

## 使用量

### IndexConfig - 管理搜索索引

这个 `IndexConfig` class 管理搜索索引配置,用于内容发现和查询.

```js
import { IndexConfig } from '@adobe/helix-shared-config';

// Load from local file
const config = await new IndexConfig()
  .withConfigPath('/path/to/helix-query.yaml')
  .init();

// Load from GitHub repository
const config = await new IndexConfig()
  .withRepo('owner', 'repo', 'ref')
  .init();

// Access index configuration
const indices = config.toJSON().indices;

// Get a specific query
const query = config.getQuery('my-index', 'my-query');

// Get query cache timeout
const cacheTimeout = config.getQueryCache('my-index', 'my-query');

// Generate query URL with parameters
const queryUrl = config.getQueryURL('my-index', 'my-query', 'owner', 'repo', {
  page: '1',
  filter: 'value'
});
```

### MountConfig - 管理山地点

这个 `MountConfig` 类管理挂载点配置,将路径映射到OneDrive,Google Drive或GitHub等外部内容源.

```js
import { MountConfig } from '@adobe/helix-shared-config';

// Load mount configuration
const config = await new MountConfig()
  .withRepo('owner', 'repo', 'ref')
  .init();

// Match a resource path to a mount point
const mountPoint = config.match('/docs/guide');

if (mountPoint) {
  console.log(mountPoint.type);    // 'onedrive', 'google', or 'github'
  console.log(mountPoint.url);     // Source URL
  console.log(mountPoint.relPath); // Relative path from mount point
}
```

支持的挂载点类型 :

-   **一驾/共享点**数字 : `https://*.sharepoint.com/...` 或者说 `onedrive:` URL( URL)
-   **谷歌驱动器**数字 : `https://drive.google.com/...` 或者说 `gdrive:` URL( URL)
-   **GitHub 图像**数字 : `https://github.com/owner/repo/tree/ref/path` URL( URL)

### SchemapConfig - 管理项目

这个 `SitemapConfig` class 管理 SEO 和内容发现的站点映射配置 .

```js
import { SitemapConfig } from '@adobe/helix-shared-config';

// Load sitemap configuration
const config = await new SitemapConfig()
  .withRepo('owner', 'repo', 'ref')
  .init();

// Add a new sitemap
const sitemap = config.addSitemap({
  name: 'main',
  origin: 'https://example.com',
  source: '/content',
  destination: '/sitemap.xml',
  lastmod: 'YYYY-MM-DD'
});

// Add language variants
config.addLanguage('main', {
  name: 'en',
  source: '/en',
  destination: '/en/sitemap.xml',
  hreflang: 'en-US',
  alternate: 'https://example.com/en'
});

// Update sitemap origin
config.setOrigin('main', 'https://www.example.com');
```

### 忽略组合 - 管理忽略模式

这个 `IgnoreConfig` 类管理类似被忽略的图案 `.gitignore`。 。 。 .

```js
import { IgnoreConfig } from '@adobe/helix-shared-config';

// Load ignore configuration
const config = await new IgnoreConfig()
  .withDirectory('/path/to/project')
  .init();

// Check if a path is ignored
const isIgnored = config.ignores('/node_modules/package');
```

### 修饰器 Config - 管理元数据修饰器

这个 `ModifiersConfig` 类管理基于 URL 模式的元数据和页眉修改符.

```js
import { ModifiersConfig } from '@adobe/helix-shared-config/modifiers';

// Parse from a sheet-like structure
const sheet = [
  { url: '/*', key: 'Cache-Control', value: 'max-age=3600' },
  { url: '/blog/*', Title: 'Blog', Description: 'Our blog' },
  { url: '/docs/**', key: 'X-Robots-Tag', value: 'noindex' }
];

const config = ModifiersConfig.fromModifierSheet(sheet);

// Get modifiers for a specific path
const modifiers = config.getModifiers('/blog/post-1');
// Returns: { 'cache-control': 'max-age=3600', 'title': 'Blog', 'description': 'Our blog' }
```

### 无服务器函数配置

使用 `requiredConfig` 或者说 `optionalConfig` 在无服务器功能中自动加载配置.

```js
import { requiredConfig, optionalConfig } from '@adobe/helix-shared-config';

// Function that requires configuration
async function handler(request, context) {
  // Configuration available in context.config
  const { fstab, index } = context.config;

  const mountPoint = fstab.match(request.url);
  // ... process request
}

// Wrap with required config - returns 400 if config is missing
export const main = requiredConfig(handler, 'fstab', 'index');

// Or use optional config - continues without config if missing
export const main = optionalConfig(handler, 'fstab', 'index');
```

包装器自动取出 `owner`, (中文(简体) ), `repo`,以及 `ref` 从请求参数中加载指定的配置.

## 配置选项

所有配置类扩展 `BaseConfig` 并支持下列备选方案:

### 正在装入配置

```js
const config = await new IndexConfig()
  .withDirectory('/path/to/dir')           // Set working directory
  .withConfigPath('/path/to/config.yaml') // Set explicit config file path
  .withSource('yaml: content')            // Provide YAML source directly
  .withJSON({ key: 'value' })            // Provide parsed JSON directly
  .withLogger(logger)                     // Set custom logger
  .init();
```

### 从 GitHub 装入

```js
const config = await new IndexConfig()
  .withRepo('owner', 'repo', 'ref', {
    headers: {
      authorization: 'token ghp_...'
    }
  })
  .withTransactionID('request-id-123')
  .init();
```

### 缓存

```js
const config = await new IndexConfig()
  .withCache({ max: 100 })  // Set cache size (max entries)
  .withRepo('owner', 'repo', 'ref')
  .init();
```

### 验证

```js
// Check for parsing errors
const errors = config.getErrors();
if (errors.length > 0) {
  console.error('Configuration errors:', errors);
}
```

## 配置文件格式

### helix-query.yaml (IndexConfig) (英语)

```yaml
version: 1
indices:
  my-index:
    include:
      - /content/**
    exclude:
      - /content/drafts/**
    target: https://example.algolia.net
    properties:
      title:
        select: head > meta[property="og:title"]
        value: attribute(el, 'content')
      description:
        select: head > meta[name="description"]
        value: attribute(el, 'content')
    queries:
      search:
        query: '{search}'
        parameters:
          - search
        hitsPerPage: 10
        cache: 600
```

### fstab.yaml (MountConfig) (法语)

```yaml
mountpoints:
  /: https://adobe.sharepoint.com/sites/example/Shared%20Documents/root
  /docs: https://github.com/owner/repo/tree/main/documentation
  /assets: https://drive.google.com/drive/folders/abc123def456
```

### helix-siteap.yaml (SiteapConfig) (英语)

```yaml
version: 1
sitemaps:
  website:
    origin: https://www.example.com
    source: /content
    destination: /sitemap.xml
    lastmod: YYYY-MM-DD
    languages:
      en:
        source: /en
        destination: /en/sitemap.xml
        hreflang: en-US
        alternate: https://www.example.com/en
```

### .hlxignore( IgnoreConfig) (英语)

```
# Ignore patterns (glob format)
node_modules/
*.tmp
.git/
.DS_Store
```

## 高级使用

### 添加/修改索引定义

```js
const config = await new IndexConfig().init();

// Add a new index
config.addIndex({
  name: 'blog',
  include: ['/blog/**'],
  exclude: ['/blog/drafts/**'],
  target: 'https://example.algolia.net',
  properties: {
    title: { select: 'h1', value: 'textContent(el)' }
  }
});

// Replace an existing index
config.replaceIndex({
  name: 'blog',
  include: ['/blog/**', '/news/**'],
  exclude: [],
  target: 'https://example.algolia.net',
  properties: {}
});

// Remove an index
config.removeIndex({ name: 'blog' });

// Save changes
await config.saveConfig();
```

### 使用配置源

```js
// Export to YAML
const yamlString = config.toYAML();

// Export to JSON
const jsonObject = config.toJSON();

// Get raw source
const source = config.source;

// Get version
const version = config.version;
```

## 处理错误

配置类包括稳健的错误处理 :

```js
try {
  const config = await new IndexConfig()
    .withRepo('owner', 'repo', 'ref')
    .init();

  const errors = config.getErrors();
  if (errors.length > 0) {
    // Handle YAML parsing errors
    errors.forEach(error => console.error(error.message));
  }
} catch (e) {
  // Handle loading errors
  console.error('Failed to load configuration:', e);
}
```

## 许可证

阿帕奇 - 2.0

## 常见问题

### @adobe/helix-shared-config 是什么？

Helix 项目共享模块 - 配置

### 如何安装 @adobe/helix-shared-config？

在项目目录运行 npm install @adobe/helix-shared-config，或使用 pnpm add / yarn add / bun add。

### @adobe/helix-shared-config 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @adobe/helix-shared-config 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @adobe/helix-shared-config 可以商用吗？

@adobe/helix-shared-config 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @adobe/helix-shared-config 的下载量有多少？

根据 npm 官方下载统计，@adobe/helix-shared-config 在 2026/10/05 – 2026/11/03 这 30 天内被下载 32,053 次，日均约 1,068 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @adobe/helix-shared-config 还在维护吗？

最新版本 11\.2\.7 发布于 2026/10/20（18 天前）；至今共发布 189 个版本，其中过去 12 个月发布了 26 个；首次发布于 2021/04/29。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

