Skip to content

optimizePackageImports silently skips TypeScript barrels (export map parsed as JS) #5128

Backlog

Description

@quantizor

Summary

optimizePackageImports silently does nothing for a package whose barrel is TypeScript source (common for monorepo workspace packages that export .ts directly). The barrel's export map comes back empty, so every import from that package stays a whole-barrel import.

Mechanism

buildExportMapFromFile in dist/plugins/optimize-imports.js reads the barrel file from disk and calls parseProgram(content). parseProgram (dist/plugins/ast-utils.js) always parses with the filename file.js, so the file is parsed as JavaScript. Any TypeScript-only syntax in the barrel (export type { ... }, export { type X, y }, type annotations) throws, and the catch returns an empty Map. Nothing is logged.

The transform handler itself is fine, because it parses already-stripped JS. Only the export-map build reads raw source.

A second, smaller problem: the cached export maps are cleared only in buildStart. In dev, editing a barrel or one of its origin files (adding, removing or moving an export) leaves the old map in place until the server restarts.

Reproduction

  1. A workspace package pkg with "sideEffects": false and src/index.ts:
    export type { Shape } from "./shape";
    export { area } from "./area";
  2. next.config.ts: experimental: { optimizePackageImports: ["pkg"] }.
  3. A server module: import { area } from "pkg";
  4. Run the dev server and inspect the transformed module (or call the exported buildBarrelExportMap on src/index.ts).

Expected: the import is rewritten to ./area. Actual: the export map is empty and the import is left as from "pkg". Removing the export type line makes it work.

Suggested fix

Pass the language for the file being parsed (for example lang derived from the file extension, as the transform path does) to parseProgram in buildExportMapFromFile, and drop cached export maps for a file (and the barrels that reached it) on watchChange / hotUpdate.

Versions: vinext 1.4.7, Vite 8.3.1.

Activity

  1. added
    bug
    on Dec 4, 2026
  2. alcora-dev commented on Dec 4, 2026

    @alcora-dev
    Contributor

    Triage: reproduced

    Thanks for the detailed report. I can confirm this on the current code. When a barrel file, or a file it reaches through export *, contains TypeScript syntax such as export type { Shape } from "./shape", export { type Shape, area } or type annotations, the barrel analysis reads the file as plain JavaScript and the parse fails. The failure is swallowed, the export map comes back empty, and import { area } from "pkg" stays a whole-barrel import without any warning. The cause is what you described: the export map step reads raw source but doesn't pass the file's language to the parser. Until it's fixed, a barrel without TypeScript-only syntax (for example, dropping the export type lines) gets optimised. The dev-mode caching problem you mention is real too, from reading the code: the barrel analysis cache is only reset when the build starts, so in dev, changes to a barrel's exports aren't picked up until a restart.

    Details for maintainers

    Cause: buildExportMapFromFile parses each barrel file's raw source with parseProgram(content), which always uses lang "js". Any TypeScript-only syntax in a barrel or in an export * target (export type, inline type specifiers, type annotations) makes the parse fail. The catch returns an empty export map without logging, so optimizePackageImports leaves the import pointing at the whole barrel. Also confirmed by reading the code only: export map caches are cleared only in buildStart, and there is no watchChange/hotUpdate invalidation in dev. The Next.js reference probe was skipped because a TS barrel being parseable is not in doubt.

    Where to look:

    Reproduction: npx vp test run tests/optimize-imports-ts-barrel.repro.test.ts
    The command exited with 1 on a clean checkout.

    Expected: buildBarrelExportMap on a .ts barrel containing export type { Shape } from "./shape"; export { area } from "./area"; maps area to <dir>/area, so the import is rewritten.
    Observed: The export map is empty (map.get("area") is undefined) because the TypeScript source is parsed as JS, the parse throws, and the error is swallowed.

    The test: tests/optimize-imports-ts-barrel.repro.test.ts
    /**
     * Reproduction for #5128: optimizePackageImports silently skips TypeScript
     * barrels because the barrel's raw source is parsed as plain JS.
     */
    import { describe, it, expect } from "vite-plus/test";
    import * as path from "node:path";
    import { buildBarrelExportMap } from "../packages/vinext/src/plugins/optimize-imports.js";
    
    describe("buildBarrelExportMap with a TypeScript barrel", () => {
      it("maps value exports in a .ts barrel that also has `export type`", async () => {
        const entryPath = path.posix.join("/virtual/ts-barrel-repro/pkg/src", "index.ts");
        const barrelCode = `export type { Shape } from "./shape";
    export { area } from "./area";`;
    
        const map = await buildBarrelExportMap(entryPath, () => Promise.resolve(barrelCode));
    
        expect(map).not.toBeNull();
        expect(map!.get("area")).toEqual({
          source: "/virtual/ts-barrel-repro/pkg/src/area",
          isNamespace: false,
          originalName: "area",
        });
      });
    
      it("maps exports in a .ts barrel using inline `type` specifiers", async () => {
        const entryPath = "/virtual/ts-barrel-repro-inline/pkg/src/index.ts";
        const barrelCode = `export { type Shape, area } from "./area";`;
    
        const map = await buildBarrelExportMap(entryPath, () => Promise.resolve(barrelCode));
    
        expect(map!.get("area")?.source).toBe("/virtual/ts-barrel-repro-inline/pkg/src/area");
      });
    
      it("follows `export *` into a .ts sub-module with type annotations", async () => {
        const entryPath = "/virtual/ts-barrel-repro-star/pkg/src/index.js";
        const files: Record<string, string> = {
          [entryPath]: `export * from "./area";`,
          "/virtual/ts-barrel-repro-star/pkg/src/area.ts": `export function area(r: number): number { return r * r; }`,
        };
    
        const map = await buildBarrelExportMap(entryPath, (p) => Promise.resolve(files[p] ?? null));
    
        expect(map!.get("area")?.source).toBe("/virtual/ts-barrel-repro-star/pkg/src/area.ts");
      });
    });
    What it printed
    RUN  v5.1.0 /workspace/repo
    
     ❯  unit  tests/optimize-imports-ts-barrel.repro.test.ts (3 tests | 3 failed) 21ms
       ❯ buildBarrelExportMap with a TypeScript barrel (3)
         × maps value exports in a .ts barrel that also has `export type` 10ms
         × maps exports in a .ts barrel using inline `type` specifiers 2ms
         × follows `export *` into a .ts sub-module with type annotations 2ms
    
     Test Files  1 failed (1)
          Tests  3 failed (3)
       Start at  19:52:44
       Duration  799ms (setup 48%, import 34%, transform 13%, tests 4%, worker 2%)
    
    
    
    
    
    
    ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 3 ⎯⎯⎯⎯⎯⎯⎯
    
     FAIL   unit  tests/optimize-imports-ts-barrel.repro.test.ts > buildBarrelExportMap with a TypeScript barrel > maps value exports in a .ts barrel that also has `export type`
    AssertionError: expected undefined to deeply equal { …(3) }
    
    - Expected:
    {
      "isNamespace": false,
      "originalName": "area",
      "source": "/virtual/ts-barrel-repro/pkg/src/area",
    }
    
    + Received:
    undefined
    
     ❯ tests/optimize-imports-ts-barrel.repro.test.ts:18:30
         16|
         17|     expect(map).not.toBeNull();
         18|     expect(map!.get("area")).toEqual({
           |                              ^
         19|       source: "/virtual/ts-barrel-repro/pkg/src/area",
         20|       isNamespace: false,
    
    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/3]⎯
    
     FAIL   unit  tests/optimize-imports-ts-barrel.repro.test.ts > buildBarrelExportMap with a TypeScript barrel > maps exports in a .ts barrel using inline `type` specifiers
    AssertionError: expected undefined to be '/virtual/ts-barrel-repro-inline/pkg/s…' // Object.is equality
    
    - Expected:
    "/virtual/ts-barrel-repro-inline/pkg/src/area"
    
    + Received:
    undefined
    
     ❯ tests/optimize-imports-ts-barrel.repro.test.ts:31:38
         29|     const map = await buildBarrelExportMap(entryPath, () => Promise.re…
         30|
         31|     expect(map!.get("area")?.source).toBe("/virtual/ts-barrel-repro-in…
           |                                      ^
         32|   });
         33|
    
    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/3]⎯
    
     FAIL   unit  tests/optimize-imports-ts-barrel.repro.test.ts > buildBarrelExportMap with a TypeScript barrel > follows `export *` into a .ts sub-module with type annotations
    AssertionError: expected undefined to be '/virtual/ts-barrel-repro-star/pkg/src…' // Object.is equality
    
    - Expected:
    "/virtual/ts-barrel-repro-star/pkg/src/area.ts"
    
    + Received:
    undefined
    
     ❯ tests/optimize-imports-ts-barrel.repro.test.ts:43:38
         41|     const map = await buildBarrelExportMap(entryPath, (p) => Promise.r…
         42|
         43|     expect(map!.get("area")?.source).toBe("/virtual/ts-barrel-repro-st…
           |                                      ^
         44|   });
         45| });
    
    ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/3]⎯
    

    Triaged by an AI agent at 5974ee6; it may be wrong. Confidence: high. · Triage report · Run #133

  3. alcora-dev commented on Dec 4, 2026

    @alcora-dev
    Contributor

    A fix is ready for review: #5129

    A pull request fixes this, with the reproduction kept as a regression test. ask-bonk[bot] approved its head, and its checks pass: it is waiting for a maintainer.

    Fixed by an AI agent; it may be wrong. · Triage report · Run #1241

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions