@graphox/swc-plugin

中文文档
1.5.2发布于 2026/11/16MITTypeScriptES Module构建来源已验证近 30 天下载 3万

SWC plugin for Graphox: rewrites graphql() calls to direct generated-document imports so unused documents are tree-shaken

原始使用文档
文档目录17 节
  1. Overview
  2. Prerequisites
  3. Installation
  4. Requirements
  5. Host versions
  6. Usage
  7. rsbuild Configuration
  8. Next.js Configuration
  9. Multiple Projects
  10. Cross-project imports
  11. Configuration Options
  12. Local Development
  13. emitExtensions
  14. Fragment Documents
  15. Building from Source
  16. See Also
  17. License

@graphox/swc-plugin

Overview

Pre-built SWC plugin for Graphox codesplitting. This package bundles the WASM binary for easy use with rsbuild, Turbopack, or native SWC.

Prerequisites

Building the WASM plugin from source requires:

  • Rust toolchain: pinned in rust-toolchain.toml — rustup installs it, and the wasm32-wasip1 target, automatically
  • Node.js 22.13+ (required by pnpm 11)
  • pnpm 11: corepack enable && corepack install -g pnpm@latest

For users of the pre-built package, only Node.js 18+ is required.

Installation

pnpm add @graphox/swc-plugin

Requirements

  • Node.js 18+
  • rsbuild, Turbopack, or native SWC

Host versions

The plugin ships as a WASM module compiled against a specific swc_core, and an SWC host only runs it if its own swc_core is at least as new. Each host embeds swc_core on its own schedule, so the floors differ:

hostminimum
@swc/core1.15.0
@rspack/core, and @rsbuild/core through it2.2.0

On an older host the build fails with failed to invoke plugin, usually with a hint naming the host's swc_core version. Upgrade the host — the plugin cannot work around it.

Usage

rsbuild Configuration

// rsbuild.config.ts
import { defineConfig } from '@rsbuild/core';
import { createSWCPlugin } from '@graphox/swc-plugin';
import path from 'path';

export default defineConfig({
  source: {
    alias: {
      '__generated__': path.resolve(__dirname, './__generated__'),
    },
  },
  tools: {
    swc: {
      jsc: {
        parser: {
          syntax: 'typescript',
          tsx: true,
        },
        experimental: {
          plugins: [
            createSWCPlugin({
              manifestPath: './__generated__/manifest.json',
              outputDir: './__generated__'
            })
          ],
        },
      },
    },
  },
});

Next.js Configuration

// next.config.mjs
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createSWCPlugin } from '@graphox/swc-plugin';

const appDir = path.dirname(fileURLToPath(import.meta.url));
// Turbopack passes the plugin each module's path relative to this directory:
// here the root of a workspace two levels above the app
const root = path.join(appDir, '..', '..');

/** @type {import('next').NextConfig} */
const nextConfig = {
  turbopack: { root },
  experimental: {
    swcPlugins: [
      createSWCPlugin({
        outputs: [{ outputDir: path.join(appDir, '__generated__') }],
        root,
      }),
    ],
  },
};

export default nextConfig;

Set turbopack.root and root to the same directory: the workspace root in a monorepo, the app's directory otherwise. Webpack builds pass absolute paths and ignore root.

Multiple Projects

A workspace whose modules resolve GraphQL against several output directories should register them all in one plugin instance:

graphox.createSWCPlugin({
  outputs: [
    { outputDir: path.resolve(__dirname, 'app/graphql') },
    { outputDir: path.resolve(repoRoot, 'packages/auth/graphql') },
    { outputDir: path.resolve(repoRoot, 'packages/catalog/graphql') },
  ],
})

One instance per output is expensive and incomplete:

  • Cost. SWC serializes the whole AST into the plugin and back for every plugin on every module, whether or not the plugin changes anything. A module belongs to exactly one output, so with N instances, N−1 of those round-trips per module are guaranteed no-ops.
  • Correctness. An instance only knows its own project, so it cannot rewrite an import that crosses a project boundary. With every output registered together, a document imported from another project's entrypoint is redirected straight at that project's generated file.

Cross-project imports

Within the package that owns an output, documents are imported by relative path. Crossing a package boundary, a relative path would reach past the package's subpath exports, so the import goes through the package's public specifier instead:

// packages/storefront/graphql/storefront.codegen.ts, before
import { ProductCardFragmentDoc } from "@example/catalog/graphql";

// after
import { ProductCardFragmentDoc } from "@example/catalog/graphql/catalog.codegen";

That requires the owning package to export the files inside its output directory, not just the entrypoint:

{
  "name": "@example/catalog",
  "exports": {
    "./graphql": "./graphql/index.ts",
    "./graphql/*": "./graphql/*"
  }
}

The plugin infers the specifier from the package's name and exports, and warns naming the exact entry to add when the wildcard is missing. Inference is deliberately conservative — it only fires when exactly one exports subpath resolves to the output directory — so set importAlias explicitly for a package with no exports field, or one resolved only through bundler aliases.

Document names and sources may repeat across outputs. Two projects defining SetPriceMutationDocument, even with identical source text, is fine: resolution is scoped to the entrypoint an import came from rather than searched across a merged map.

Output directories must be distinct, and must not nest.

Configuration Options

OptionTypeRequiredDescription
outputsobject[]Yes*One entry per project; see below. Preferred over the single-output fields
emitExtensionsstringNoFile extension for generated imports: "none" (default), "ts", "js", "dts"
rootstringNoDirectory the host's module paths are relative to, for a host that passes relative ones (Turbopack). Resolved against cwd

Each entry in outputs:

OptionTypeRequiredDescription
outputDirstringYesDirectory containing generated files
manifestPathstringNoPath to manifest.json. Defaults to <outputDir>/manifest.json
manifestDataobject[]NoInline manifest data, used instead of manifestPath
graphqlImportPathsstring[]NoExtra import paths to treat as GraphQL entrypoints
importAliasstringNoPublic specifier for this output, e.g. @example/catalog/graphql. Inferred from the package's name and exports
packageRootstringNoRoot of the package owning this output. Inferred as the directory of the nearest package.json

*The single-output form — outputDir, manifestPath, manifestData, graphqlImportPaths, importAlias and packageRoot at the top level — is still accepted and behaves as a one-element outputs.

Local Development

You can override the WASM plugin path by setting the GRAPHOX_SWC_PLUGIN_PATH environment variable. This is useful for testing local builds of the Rust plugin without copying files.

export GRAPHOX_SWC_PLUGIN_PATH=$(pwd)/target/wasm32-wasip1/release/graphox_swc_plugin.wasm

The override is an absolute path, which Turbopack does not load.

emitExtensions

Controls the file extension appended to generated import paths. Should match the emit_extensions setting in your graphox.yaml:

ValueResult
"none" (default)import { X } from "./file.codegen"
"ts"import { X } from "./file.codegen.ts"
"js"import { X } from "./file.codegen.js"
"dts"import { X } from "./file.codegen.d.ts"

Fragment Documents

When generate_ast_for_fragments: true is enabled in your config, fragment documents are also included in the manifest and will be properly rewritten by the plugin.

A fragment without a document, such as a @type_only one, is listed in the manifest by its source alone. The plugin replaces its graphql() call with {}, the value graphql.ts returns for it, so ResultOf<typeof Doc> still types it.

With graphql_tag_fallback: true, graphql.ts parses such a fragment at runtime instead, which the plugin cannot do. The fragment is then left out of the manifest, and the plugin fails the build on its graphql() call.

Building from Source

If you need to rebuild the WASM plugin:

# Install dependencies
pnpm install

# Build TypeScript only (requires pre-built WASM)
pnpm run build

# Build WASM only (requires Rust toolchain)
pnpm run build:wasm

# Build everything (TypeScript + WASM)
pnpm run build:all

# Run tests
pnpm test

See Also

License

MIT — see LICENSE.

版本与发布记录

@graphox/swc-plugin 共发布 45 个版本,首次发布于 2026/02/26;过去 12 个月发布了 45 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.5.2latest2026/11/16今天
1.5.12026/11/16今天
1.5.02026/11/124 天前
1.4.12026/11/0115 天前
1.4.02026/10/2819 天前
1.3.02026/10/2621 天前

关于 @graphox/swc-plugin 的常见问题

@graphox/swc-plugin 是什么?

SWC plugin for Graphox: rewrites graphql() calls to direct generated-document imports so unused documents are tree-shaken

如何安装 @graphox/swc-plugin?

在项目目录运行 npm install @graphox/swc-plugin,或使用 pnpm add / yarn add / bun add。

@graphox/swc-plugin 支持 TypeScript 吗?

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

@graphox/swc-plugin 支持 ESM 还是 CommonJS?

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

@graphox/swc-plugin 需要什么版本的 Node.js?

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

@graphox/swc-plugin 可以商用吗?

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

@graphox/swc-plugin 的下载量有多少?

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

@graphox/swc-plugin 还在维护吗?

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