@graphql-tools/external-fragment-loader

中文文档
1.0.10发布于 2026/11/10MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2.2万

A GraphQL loader that resolves cross-package fragment dependencies from external packages

原始使用文档
文档目录11 节
  1. Installation
  2. Three API entry points
  3. 1. Default loader export (for GraphQL Code Generator)
  4. 2. Class-based loader
  5. 3. Direct resolver API
  6. AST locations
  7. Caching
  8. Using filters
  9. Filtering files by content
  10. Filtering dependency packages by name
  11. Filtering by package dependencies

@graphql-tools/external-fragment-loader

Resolves missing GraphQL fragments by following direct and transitive dependencies in package.json, loading only the external fragments the package needs.

Installation

npm install @graphql-tools/external-fragment-loader

The resolver requires a target (consumer) package directory and one or more directories containing its dependency packages:

const options = {
  packageDir: '/path/to/packages/my-app',
  externalPackagesDirs: ['/path/to/packages']
}

packageDir and externalPackagesDirs should be absolute paths. By default, the loader scans src directory in the above packages for .ts, .tsx, .js, .jsx, .graphql, and .gql files. These defaults can be changed with the options described in options.ts.

Three API entry points

Entry pointReturnsUse it when
Default exportDocumentNode (or Promise<DocumentNode> with async: true)Configuring a Codegen or GraphQL Tools custom loader; uses the synchronous resolver by default
ExternalFragmentLoaderSource[] with document, rawSDL, and locationUsing @graphql-tools/load programmatically (can be async)
resolveExternalFragmentsFile metadata, including filePath and fragment definitionsBuilding a file list or another custom workflow

Each entry point has a synchronous variant where applicable. The async and sync variants are:

  • async: true / async: false
  • ExternalFragmentLoader.load() / ExternalFragmentLoader.loadSync()
  • resolveExternalFragments() / resolveExternalFragmentsSync()

1. Default loader export (for GraphQL Code Generator)

The default export returns a single merged DocumentNode. This is the simplest option for GraphQL Code Generator because Codegen's custom-loader path expects one DocumentNode or one Source.

This is a sample of code generation for packages/my-package. The script runs from the monorepo root.

import { resolve } from 'node:path'
import type { CodegenConfig } from '@graphql-codegen/cli'

const packageDir = resolve('packages/my-package')
const externalPackagesDir = resolve('packages')

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: ['./packages/my-package/src/**/*.graphql'],
  externalDocuments: [
    {
      // a pointer that triggers the custom loader for the consumer package
      [packageDir]: {
        loader: '@graphql-tools/external-fragment-loader',
        packageDir,
        externalPackagesDirs: [externalPackagesDir],
        async: true // codegen can consume Promise<DocumentNode> directly
      }
    }
  ],
  generates: {
    './packages/my-package/src/__generated__/types.ts': {
      plugins: ['typescript', 'typescript-operations']
    }
  }
}

export default config

Use at most one external-fragment pointer for each packageDir in a Codegen configuration. The loader returns all required external fragments for that package; repeating the pointer causes those fragments to be loaded more than once and can produce duplicate fragment definitions. Normal document pointers can still be listed alongside the single external-fragment pointer.

The default export uses the synchronous resolver unless async: true is set. With async: true, it returns a Promise<DocumentNode> and uses the asynchronous resolver. Use this option with Codegen or another asynchronous loading API; omit it or set it to false when using loadDocumentsSync.

2. Class-based loader

Use ExternalFragmentLoader when calling @graphql-tools/load directly or when you need the individual Source objects:

import { ExternalFragmentLoader } from '@graphql-tools/external-fragment-loader'

const loader = new ExternalFragmentLoader()

const sources = await loader.load('.', {
  packageDir,
  externalPackagesDirs: [externalPackagesDir]
})

To register the class with @graphql-tools/load, pass it in the loaders option for the pointer that represents the external-fragment document:

import { loadDocuments } from '@graphql-tools/load'

const sources = await loadDocuments(['./external-fragments.graphql'], {
  loaders: [loader],
  packageDir,
  externalPackagesDirs: [externalPackagesDir]
})

The loader also exposes a synchronous method:

const syncSources = loader.loadSync('.', options)

Each returned source contains the parsed document, the matching rawSDL, and the provider file's location. When registering the class with @graphql-tools/load, use one external-fragment pointer for each package being resolved. The loader does not de-duplicate separate invocations for repeated pointers.

3. Direct resolver API

Use the resolver functions when you need the external file list or fragment metadata rather than a GraphQL Tools loader result:

import {
  resolveExternalFragments,
  resolveExternalFragmentsSync
} from '@graphql-tools/external-fragment-loader'

const files = await resolveExternalFragments(options)
const syncFiles = resolveExternalFragmentsSync(options)

The result has this shape:

[
  {
    filePath: '/path/to/packages/shared/src/user-fields.graphql',
    packageName: '@example/shared',
    definitions: [{ name: 'UserFields', typeCondition: 'User' }]
  }
]

This API returns file metadata, not parsed ASTs. Passing the returned filePath values as Codegen documents/externalDocuments works, but Codegen will read and parse those files again. Use the default loader or the class-based loader when you want to reuse the parsed documents.

AST locations

noLocation defaults to true. Set it to false to retain source locations on parsed fragments.

With Codegen's extractAllFieldsToTypesCompact: true, this can affect type reuse for identical selections. The examples below use simplified names; exact output depends on the Codegen version and configuration.

// noLocation: true — both fields reuse the same generated type
type AddressFields = { street: string; city: string }
type QueryResult = {
  primaryAddress: AddressFields
  secondaryAddress: AddressFields
}
// noLocation: false — separate locations can produce separate types with the same shape
type PrimaryAddressFields = { street: string; city: string }
type SecondaryAddressFields = { street: string; city: string }
type QueryResult = {
  primaryAddress: PrimaryAddressFields
  secondaryAddress: SecondaryAddressFields
}

Caching

Package fragment maps, parsed sources, and package.json dependency metadata are cached between resolver calls. Consumer package maps are not normally retained unless the consumer package was previously loaded as a provider.

When running the loader in watch mode — for example, to run Codegen in the background while using an IDE so that the package's generated GraphQL types are regenerated automatically whenever a file changes — consider setting the following options:

  • Set invalidateTargetPackageCache: true to invalidate the cached fragment map and package.json dependency metadata for the target package specified by packageDir before each resolution call. This prevents stale data when a package that was previously cached as a provider is later scanned as the consumer.

  • Set cacheTTL (for example, to 10000 for 10 seconds) so cached provider data eventually expires. This helps avoid stale data when a provider package is updated indirectly, for example by a git merge, while the watch process is still running.

Using filters

The filters are optional pre-filters: they run before the expensive dependency scanning and GraphQL parsing work. Restricting the package names and files early can be faster than parsing every source file in every dependency package.

In a benchmark of the large monorepo this loader was written for, the approximate observed time reductions were as follows (with total reduction of 68%):

  • fileContentFilter: 60%
  • packageNameFilter: 4%
  • packageDependencyFilter: 4%

Filtering files by content

Use fileContentFilter to skip source files that don't contain GraphQL. The file content is read once and passed to the predicate, but files returning false are not parsed or plucked for GraphQL documents:

const options = {
  packageDir,
  externalPackagesDirs,
  fileContentFilter: (content, filePath) => {
    // Keep standalone GraphQL files and match GraphQL tags or magic comments in code files.
    return (
      /\.(graphql|gql)$/.test(filePath) ||
      /\b(?:gql|graphql)\s*`/.test(content) ||
      /\/\*\s*graphql\s*\*\//i.test(content)
    )
  }
}

This is especially useful when packages contain many TypeScript or JavaScript files but only a small number of them contain GraphQL tags. A file-content filter should be broad enough not to exclude custom GraphQL tag identifiers that are configured through pluckConfig.

Filtering dependency packages by name

Use packageNameFilter to limit which package.json dependencies are considered as providers. The filter is applied to direct and transitive dependency names before their files are scanned:

const options = {
  packageDir,
  externalPackagesDirs,
  packageNameFilter: packageName =>
    packageName.startsWith('my-company-name-') || packageName === 'shared-graphql'
}

Packages rejected by this filter are not searched. If a required fragment is defined in a rejected package, the resolver reports it as unresolved.

Filtering by package dependencies

Use packageDependencyFilter to skip scanning packages that don't use GraphQL, without affecting dependency traversal. The filter receives the merged dependencies and devDependencies record from each package's package.json by default, or only dependencies when includeDevDependencies is false. It returns boolean. Packages that return false are still traversed for their own transitive dependencies — they are just not scanned for fragment definitions:

const options = {
  packageDir,
  externalPackagesDirs,
  packageDependencyFilter: deps => '@apollo/client' in deps
}

This is useful in large monorepos where many packages don't contain GraphQL but sit in the dependency chain between the consumer and the packages that do. Without this filter, every reachable package gets its source files globbed and read. With the filter, only packages that pass the predicate are scanned, while non-GraphQL intermediaries are still traversed so that GraphQL packages behind them are found:

A (consumer) → B (no GraphQL) → C (has GraphQL)

版本与发布记录

@graphql-tools/external-fragment-loader 共发布 185 个版本,首次发布于 2026/10/15;过去 12 个月发布了 185 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.0.10latest2026/11/106 天前
1.0.10-alpha-20261109221325-ed80bc4039e55bcc63d85618f1d721220233b4c8alpha2026/11/107 天前
1.0.10-alpha-20261109221124-bb0f29dbe1ab6b0fa8a7f303713895ff442abece2026/11/107 天前
1.0.10-alpha-20261109214254-d9f6ab1d5fd82c024b5bcb7506596d130502ed992026/11/107 天前
1.0.10-alpha-20261109213113-8db32f97a1eb80b7752626d7921023ff21515bb32026/11/107 天前
1.0.10-alpha-20261109213007-e187af779a0e0f6b0a71981ce8b90054eb887f7f2026/11/107 天前

其他发布通道:rc → 1.0.8-rc-20261026131423-8fabaf53c1774b23fb7f57b7dadfe5d6b5213dac,alpha → 1.0.10-alpha-20261109221325-ed80bc4039e55bcc63d85618f1d721220233b4c8。

关于 @graphql-tools/external-fragment-loader 的常见问题

@graphql-tools/external-fragment-loader 是什么?

A GraphQL loader that resolves cross-package fragment dependencies from external packages

如何安装 @graphql-tools/external-fragment-loader?

在项目目录运行 npm install @graphql-tools/external-fragment-loader,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:graphql(^16.0.0 || ^17.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@graphql-tools/external-fragment-loader 支持 TypeScript 吗?

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

@graphql-tools/external-fragment-loader 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@graphql-tools/external-fragment-loader 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.18.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@graphql-tools/external-fragment-loader 可以商用吗?

@graphql-tools/external-fragment-loader 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@graphql-tools/external-fragment-loader 的下载量有多少?

根据 npm 官方下载统计,@graphql-tools/external-fragment-loader 在 2026/10/17 – 2026/11/15 这 30 天内被下载 21,648 次,日均约 722 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@graphql-tools/external-fragment-loader 还在维护吗?

最新版本 1.0.10 发布于 2026/11/10(6 天前);至今共发布 185 个版本,其中过去 12 个月发布了 185 个;首次发布于 2026/10/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。