Skip to content

refactor(fmt): use the official SWC Next formatter plugin - #648

Draft
SoonIter wants to merge 10 commits into
mainfrom
refactor-official-swc-next-prettier-plugin
Draft

SoonIter wants to merge 10 commits into
mainfrom
refactor-official-swc-next-prettier-plugin

Conversation

@SoonIter

@SoonIter SoonIter commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Use @swc-next/formatter-prettier-plugin for default JS/TS formatting and JavaScript, JSX, TypeScript and TSX code fences in Markdown/MDX.

SWC Next Prettier plugin vs. SWCFMT Prettier plugin

Both use the SWC Next parser. The difference is who builds the formatting document:

Before · SWC Next Prettier plugin
Source
  → SWC Next parser (Rust)
  → JavaScript AST → local AST adapter
  → Prettier ESTree printer (JavaScript) → Prettier Doc
  → Prettier renderer → formatted text

After · SWCFMT Prettier plugin
Source
  → SWC Next parser (Rust) → AST
  → SWC Next formatter (Rust) → Doc IR
  → binary Doc IR → plugin decodes into Prettier Doc
  → Prettier renderer → formatted text

Before uses local swcNextPlugin.ts + @swc-next/parser; after uses the official @swc-next/formatter-prettier-plugin.

Doc IR is a layout description—text, groups, indentation and possible line breaks. SWCFMT moves AST-to-Doc work into Rust; Prettier still chooses the final line breaks and renders the text.

For Markdown/MDX, Prettier formats the document and delegates supported code fences to SWCFMT. The wrapper supplies missing language aliases (js, ts, etc.) and a JSX language entry so fence language inference selects SWCFMT. MDX top-level import/export and JSX nodes still use Prettier's specialized processing.

Behavior also changes:

Area Before → After
Ambient module import attributes Error → Formatted, attributes preserved
Embedded HTML/CSS/GraphQL in JS/TS Formatted → Preserved as-is
Range/pragma, some layout options, import source Supported → Error on the SWC file path (exact cases below)
Rsbuild formatting output 25 files differ: 17 JS/TS files and 8 Markdown/MDX files

Rsbuild formatting CLI, median elapsed time:

Scope Before After Time saved oxfmt 0.79.0 reference
JS/TS · 2,403 files 652 ms 467 ms 28.5% 188 ms
Markdown/MDX · 477 files 939 ms 887 ms 5.5% 948 ms
All supported types · 3,439 files 1,530 ms 1,302 ms 14.9% 1,073 ms

oxfmt is an external CLI reference on the same files. These runs use each CLI's default concurrency: 8 workers for rs fmt, 18 threads for oxfmt. Configuration, plugin and output differences are documented below. Each scope runs independently; the rows cannot be added or subtracted to derive other language timings.

Behavior before / after

These comparisons use the PR base (d1efeb3) and final implementation (fc75027), with default formatting unless stated otherwise.

  • Markdown/MDX code fences: JS/TS code fences use SWCFMT; the host document remains with Prettier, including configured Markdown plugins. embeddedLanguageFormatting: 'off' leaves code fences untouched. Project JS/TS parser plugins retain precedence. MDX top-level import/export requires AST validation and JSX uses Prettier's expression/root-marker handling; these nodes remain on Prettier's built-in path.
  • Rsbuild document coverage: 2,891 code fences successfully use SWCFMT across 477 Markdown/MDX files. Another 14 snippets are rejected, including incomplete examples, mismatched language labels and unsupported syntax. Prettier's Markdown embed handling preserves those snippets verbatim. Eight documents change only in code-fence layout; AST/comment comparisons pass and all documents are stable on a second format.
  • Ambient module attributes: declare module "*" with { type: "text" } { ... } errors before; after it formats and preserves the attributes.
  • Embedded languages inside JS/TS templates: recognized HTML, CSS and GraphQL template contents are formatted before, but preserved as-is after, even with embeddedLanguageFormatting enabled. This also applies inside JS/TS code fences. For example, the GraphQL body in const query = /* GraphQL */ `query{user{id name}}` stays compact.
  • Range formatting: standalone SWC formatting supports whole files only. A positive rangeStart or any finite rangeEnd produces an error.
  • Pragma options: requirePragma, insertPragma and checkIgnorePragma produce errors on standalone SWC files, including empty files and files without a pragma.
  • Layout options: objectWrap: 'collapse', experimentalTernaries: true and experimentalOperatorPosition: 'start' produce errors on standalone SWC files.
  • Source-phase imports: import source mod from './module.wasm' formats before and produces an unsupported import-phase error after on the standalone SWC path. The Rsbuild fixture exits with code 2 rather than code 0. Inside Markdown, rejected embedded snippets are preserved by the host.
  • Parser selection: default JS/TS uses the official swc / swc-ts / swc-tsx parsers. Explicit babel / typescript selection uses Prettier, and project JS/TS parser plugins retain precedence. Existing swc-next / swc-next-ts names remain available.
  • Other hosts: Vue and Svelte scripts continue using their corresponding Prettier formatters.

The SWC Next formatter remains experimental. Projects needing Prettier's JS/TS template-language formatting or the standalone options listed above can explicitly select parser: 'babel' or parser: 'typescript' in define.fmt() or a file override.

Prettier stays at 3.10.1, matching the PR base. Upstream SWC Next #754 declares the plugin's Prettier peer as catalog:, which expands to the workspace's pinned 3.9.9 when published. Its description, discussion, reviews and commit messages do not identify a specific incompatibility with 3.10.1. Rstack allows exactly 3.10.1 for this peer on @swc-next/formatter-prettier-plugin@0.7.0; no plugin runtime patch is needed.

With the same published plugin, all 12,219 upstream formatter fixture/option combinations produce identical output under Prettier 3.9.9 and 3.10.1, with no errors. All 3,439 Rsbuild files, including 477 Markdown/MDX documents, also produce identical output between those two versions and pass a second format check. These checks establish compatibility for the tested corpus, not every possible input. The overall PR still changes 25 files relative to the previous SWC parser integration.

Performance methodology and oxfmt reference
  • Compared PR base d1efeb3, final implementation fc75027 and npm oxfmt@0.79.0, using isolated copies of Rsbuild at ad8388c. All implementations use exactly the same file lists and original contents. The Rstack versions use the same Rsbuild configuration, ignores and heading-case plugin.
  • Apple M5 Max, 18 cores, 64 GiB; macOS 26.6.2; Node 24.20.0; pnpm 12.18.0. Eight Rstack workers and 18 oxfmt threads. Each sample starts a new process. Rstack: node <checkout>/packages/rstack/bin/rs.js fmt <file-list> --check --no-cache; oxfmt: node <oxfmt>/bin/oxfmt --check <file-list>.
  • Seven interleaved measured runs after two warmups, rotating execution order. JS/TS: 617–707 ms before, 443–483 ms after, 175–216 ms oxfmt. Markdown/MDX: 933–1,059 ms before, 856–927 ms after, 850–965 ms oxfmt. All types: 1,458–1,671 ms before, 1,259–1,427 ms after, 968–1,134 ms oxfmt. Background services remained active; timings describe this machine and input. Both Rstack versions use Prettier 3.10.1.
  • Timing includes process startup, configuration, file discovery, worker startup and formatting. Builds and output validation run separately. These are formatting times, not Rsbuild build times or isolated engine timings. All timed inputs remained unchanged.
  • oxfmt uses singleQuote: true, printWidth: 80, sortPackageJson: true, sortImports: false, jsdoc: false and embeddedLanguageFormatting: 'auto'. The file lists already apply Rsbuild exclusions. oxfmt does not load heading-case. The reference does not hold features, outputs or CPU parallelism constant.
  • All 3,439 files are processed successfully. After formatting, the final Rstack implementation passes a second check and differs from the original input in 25 files. oxfmt's output is not required to match Rstack's.
  • The same import-source fixture is excluded from all timing inputs: e2e/cases/wasm/wasm-source-import/src/index.js. The table therefore does not claim successful formatting of every repository file.
  • This measures the complete PR, including dependency and behavior changes. Benchmark scripts and raw results remain local and are not committed.
Validation
  • Passed JS/native builds and full tests on Prettier 3.10.1: 467 passed, 1 skipped. Frozen-lockfile installation with strict peer checking and pnpm check also pass.
  • Lint/type/format checks and git diff --check pass on the final revision. The website build and changed-file spelling passed before this dependency-only update. Full spelling previously reported absolute-path words in two ignored test-generated config files; changed files were clean.
  • Regression coverage checks eight fence language names in both Markdown and MDX, actual SWCFMT parser invocation, nested TSX fences, invalid snippets, CSS fences, MDX import/export and JSX, disabled embedded formatting, and project parser precedence.
  • All 3,439 measured Rsbuild files format and pass a second check. All 477 documents are idempotent. The eight changed document code blocks pass AST/comment comparison, with surrounding document structure unchanged. The 17 standalone JS/TS changes are unchanged from the previously validated SWCFMT implementation. Structural validation is not runtime validation; the Rsbuild runtime suite was not run.
  • Verified ambient module attributes, source-phase imports, embedded GraphQL, explicit Babel selection and unsupported SWC options through regression coverage and the before/after checks.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Deploying rstack-cli with  Cloudflare Pages  Cloudflare Pages

Latest commit: fc75027
Status: ✅  Deploy successful!
Preview URL: https://56665ce6.rstack-cli.pages.dev
Branch Preview URL: https://refactor-official-swc-next-p.rstack-cli.pages.dev

View logs

@SoonIter SoonIter changed the title refactor(fmt): POC official SWC Next Prettier plugin refactor(fmt): POC SWCFMT without automatic fallback Nov 16, 2026
@SoonIter SoonIter changed the title refactor(fmt): POC SWCFMT without automatic fallback refactor(fmt): use the official SWC Next formatter plugin Nov 17, 2026
@SoonIter

Copy link
Copy Markdown
Member Author

@SoonIter

SoonIter commented Nov 17, 2026 •

Copy link
Copy Markdown
Member Author

Follow-up: SWC Next #1559 (2026-11-17)

Tested swc-project/swc-next#1559 at 85b412c against its merge base c021c72, using the same Rsbuild revision and formatting options as below. Case 6 is fixed by this PR; Cases 1–5 and 7 still reproduce.

Original case Result at #1559 head Issue / relationship
1. Chains with multiline arguments Still differs swc-next-issues#487 is related, but reports a final object argument; our reduced case has an array argument. It is not listed in #1559, and is not evidence that our case is fixed.
2. Assertions in ternary branches Still differs Exact match to swc-next-issues#486, which is not listed in #1559.
3. Curried arrow property Still differs No sufficiently close issue identified in #1559's linked issues.
4. Long template receiver Still differs No sufficiently close issue identified in #1559's linked issues.
5. Array receiver followed by .map() Still differs No sufficiently close issue identified in #1559's linked issues.
6. Final object argument wrapped in as Matches the original expected output Exact match to swc-next-issues#279, explicitly addressed by #1559. Confirmed on both the reduced input and the affected solidLoader.ts hunk.
7. Template interpolation in a code fence Still differs swc-next-issues#315 concerns numeric-array substitutions. Our arithmetic/member-call substitution remains different despite that issue being listed in #1559.

All 17 original standalone files still differ from the reference. solidLoader.ts contains both Cases 2 and 6: its Case 6 hunk is fixed, but its Case 2 hunk remains. The original 8 MDX documents also still contain differing JS/TS code fences. These counts describe the original affected set, not a new whole-repository scan.

Follow-up validation details

Built the Rust formatter from the exact #1559 head and merge base in separate clean checkouts. All seven reduced inputs reproduce the original differing output at the merge base; only Case 6 changes to the reference output at the head. The head now looks through as / satisfies wrappers when selecting the final collection argument (implementation).

Rechecked the 17 complete standalone files, all 108 JS/TS code fences extracted from the 8 original MDX files, and the 7 reduced inputs. For all 132 inputs, native output matched the matching document decoder + Prettier printer, a second formatting pass was unchanged, and independently parsed Babel ASTs/comments matched after removing location/parenthesis metadata (template raw values retained). The seven reduced results were also unchanged when switching the printer from Prettier 3.9.9 to 3.10.1. MDX host formatting and the Rsbuild runtime suite were not rerun in this follow-up.

This verifies #1559's formatter behavior; rstack-cli #648 still needs an updated formatter dependency before it receives this fix.


Rechecked the Rsbuild output differences against the current PR head. The 17 files are the standalone JS/TS subset; there are also 8 Markdown/MDX files, for 25 changed files in the 3,439-file input. They fall into the 7 cases below. All 25 files are linked; solidLoader.ts appears in two cases because it has two different changes.

  • Before: PR base d1efeb3 (local SWC Next parser adapter + Prettier 3.10.1).
  • After: PR head 14e8c69 (@swc-next/formatter-prettier-plugin@0.7.0 + Prettier 3.9.9).
  • Input: Rsbuild ad8388c, using its formatting configuration (singleQuote: true, default printWidth: 80, and heading-case for documents).

Here “expected output” means the actual Before output used as the formatting-compatibility reference, not a claim that every different layout is a correctness bug. “Actual output” is the current PR's After output. The reduced inputs below were each run through both CLIs with rs fmt --stdin-filepath input.ts (or input.mdx); these are observed outputs, not handwritten examples.

All 3,439 files were rechecked: Before passes the format check; After changes 25 files and passes a second format check. Separately, Babel (babel-ts via Prettier 3.9.9) parses the 17 changed standalone files, the changed code fences and all seven reproductions to matching normalized ASTs and comments. Location/parenthesis metadata is excluded; template raw values are retained. The eight MDX documents have matching host structure. No semantic change was found by these structural checks; the Rsbuild runtime suite was not run. The previously excluded import source fixture remains outside this 3,439-file comparison.

Case 1: Method chains break before calls with multiline arguments

SWCFMT puts the receiver and chained calls on separate lines when the final call has a multiline object or array argument. This accounts for eight standalone JS/TS files and six MDX documents.

Found in Rsbuild — e2e/cases/config/bundler-chain/index.test.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

chain.plugin('extra-define').use(rspack.DefinePlugin, [
  {
    ENABLE_TEST: JSON.stringify(true),
  },
]);

Expected output (Before, PR base)

chain.plugin('extra-define').use(rspack.DefinePlugin, [
  {
    ENABLE_TEST: JSON.stringify(true),
  },
]);

Actual output (After, PR head)

chain
  .plugin('extra-define')
  .use(rspack.DefinePlugin, [
    {
      ENABLE_TEST: JSON.stringify(true),
    },
  ]);

AST / behavior comparison

Layout difference. Call order, arguments, AST and comments are unchanged.

Affected files

Case 2: Type assertions in ternary branches lose optional parentheses

Upstream tracking: swc-next-issues#486; still reproduces at #1559 head 85b412c.

SWCFMT removes the extra parentheses around as assertions in conditional branches. The affected expressions include as const, an awaited import and other asserted values.

Found in Rsbuild — packages/core/src/plugins/target.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

const esQuery = isDefaultBrowserslist
  ? 'es2017'
  : (`browserslist:${browserslist.join(',')}` as const);

Expected output (Before, PR base)

const esQuery = isDefaultBrowserslist
  ? 'es2017'
  : (`browserslist:${browserslist.join(',')}` as const);

Actual output (After, PR head)

const esQuery = isDefaultBrowserslist
  ? 'es2017'
  : `browserslist:${browserslist.join(',')}` as const;

AST / behavior comparison

Parenthesis difference. Babel parses both outputs to the same normalized AST; the assertion still applies to the same branch expression.

Affected files

Case 3: Curried arrow functions move onto the property line

For an object property whose value is an arrow returning another arrow, the first arrow moves onto the property line.

Found in Rsbuild — e2e/cases/server/compress-stream/index.test.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

const config = {
  setup:
    ({ server }) =>
    () => {
      server.middlewares.use(handler);
    },
};

Expected output (Before, PR base)

const config = {
  setup:
    ({ server }) =>
    () => {
      server.middlewares.use(handler);
    },
};

Actual output (After, PR head)

const config = {
  setup: ({ server }) =>
    () => {
      server.middlewares.use(handler);
    },
};

AST / behavior comparison

Layout difference. Both outputs retain the same nested arrow functions and body.

Affected files

Case 4: A long template receiver breaks before the method call

For a long template literal followed by .replace(), SWCFMT moves the method call to the next line and keeps its short arguments together.

Found in Rsbuild — packages/core/src/server/assets-middleware/middleware.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

function createContentRange(type: string, size: number, range?: Range): string {
  return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`.replace(
    ':',
    '/',
  );
}

Expected output (Before, PR base)

function createContentRange(type: string, size: number, range?: Range): string {
  return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`.replace(
    ':',
    '/',
  );
}

Actual output (After, PR head)

function createContentRange(type: string, size: number, range?: Range): string {
  return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`
    .replace(':', '/');
}

AST / behavior comparison

Layout difference. The template raw/cooked values, interpolation AST and .replace() arguments are unchanged.

Affected files

Case 5: An array receiver stays compact while its map call breaks

At this indentation level, SWCFMT keeps the array on one line and breaks before .map(). Before expands the array and keeps .map() attached to its closing bracket. The test wrapper is retained because indentation affects the reproduction.

Found in Rsbuild — packages/core/tests/pluginDependencies.test.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

describe('plugins', () => {
  test('sorts dependencies', () => {
    expect(result).toEqual(
      [
        { name: '1' },
        { name: '3' },
        { name: '2', pre: ['3'] },
        { name: '4' },
      ].map((p) => ({
        environment: '',
        instance: p,
      })),
    );
  });
});

Expected output (Before, PR base)

describe('plugins', () => {
  test('sorts dependencies', () => {
    expect(result).toEqual(
      [
        { name: '1' },
        { name: '3' },
        { name: '2', pre: ['3'] },
        { name: '4' },
      ].map((p) => ({
        environment: '',
        instance: p,
      })),
    );
  });
});

Actual output (After, PR head)

describe('plugins', () => {
  test('sorts dependencies', () => {
    expect(result).toEqual(
      [{ name: '1' }, { name: '3' }, { name: '2', pre: ['3'] }, { name: '4' }]
        .map((p) => ({
          environment: '',
          instance: p,
        })),
    );
  });
});

AST / behavior comparison

Layout difference. Array elements and the mapping callback are unchanged.

Affected files

Case 6: A type-asserted object argument expands the outer call

Verified fixed by swc-project/swc-next#1559 at 85b412c, matching swc-next-issues#279. Both this reduced input and the corresponding full-file hunk now match the expected output below. The original observed output is retained for reference.

An object literal with an as assertion causes SWCFMT to split the outer call arguments across lines. Before keeps the first argument and the opening object brace on the same line.

Found in Rsbuild — packages/plugin-solid/src/solidLoader.ts regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.ts, reduced reproduction)

const result = await nativeTransformAsync(String(source), {
  ...solid,
  filename,
  sourceMap: true,
} as NativeTransformOptions);

Expected output (Before, PR base)

const result = await nativeTransformAsync(String(source), {
  ...solid,
  filename,
  sourceMap: true,
} as NativeTransformOptions);

Actual output (After, PR head)

const result = await nativeTransformAsync(
  String(source),
  {
    ...solid,
    filename,
    sourceMap: true,
  } as NativeTransformOptions,
);

AST / behavior comparison

Layout difference. The object, assertion and argument order are unchanged. This file also appears in Case 2 for a separate hunk.

Affected files

Case 7: A template interpolation wraps inside a Markdown code fence

Inside a TypeScript code fence, SWCFMT splits the arithmetic expression within a long template interpolation. Before keeps the interpolation on one line. Both English and Chinese documents contain this example.

Found in Rsbuild — website/docs/en/config/performance/print-file-size.mdx regression testing.

Input / expected output / actual output / AST comparison / affected files

Input (input.mdx, reduced reproduction)

```ts title="rsbuild.config.ts"
export default {
  performance: {
    printFileSize: {
      total: ({ distPath, assets, totalSize }) => {
        return `Generated ${assets.length} files in ${distPath}, the total size is ${(totalSize / 1000).toFixed(1)} kB.`;
      },
    },
  },
};
```

Expected output (Before, PR base)

```ts title="rsbuild.config.ts"
export default {
  performance: {
    printFileSize: {
      total: ({ distPath, assets, totalSize }) => {
        return `Generated ${assets.length} files in ${distPath}, the total size is ${(totalSize / 1000).toFixed(1)} kB.`;
      },
    },
  },
};
```

Actual output (After, PR head)

```ts title="rsbuild.config.ts"
export default {
  performance: {
    printFileSize: {
      total: ({ distPath, assets, totalSize }) => {
        return `Generated ${assets.length} files in ${distPath}, the total size is ${(
          totalSize / 1000
        ).toFixed(1)} kB.`;
      },
    },
  },
};
```

AST / behavior comparison

Layout difference inside the code fence. The template raw/cooked values and interpolation AST are unchanged; the surrounding MDX document structure is unchanged.

Affected files

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant