Skip to content

Tree shaking doesn't work with Typescript barrel files #12557

@majelbstoat

Description

@majelbstoat

Bug report

I originally raised this as a discussion, but now I think it's a bug.

Describe the bug

When using a barrel file to re-export components from a single location, tree-shaking does not function correctly.

To Reproduce

I'm using Next 9.3.6 and I've arranged my components like:

  components/
    Header/
      Header.tsx
    Sidebar/
      Sidebar.tsx
    index.ts

Each component file exports a single component, like this:

export { Header }

index.ts is a barrel file that re-exports from each individual component file:

  export * from './Header/Header.tsx'
  export * from './Sidebar/Sidebar.tsx'
  // ...

I then use a couple of components in _app.tsx like:

import { Header, Sidebar } from "../components"

There's about 100 components defined, and only a couple are used in _app.tsx. But when I analyze the bundle I have a very large chunk, shared by all pages, and it contains all my components, resulting in an inflated app page size:

Screenshot 2020-05-06 09 35 32

I use a similar import strategy within pages, and every one of them appears to contain every component.

my tsconfig.json is:

  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "preserveConstEnums": true,
    "removeComments": false,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "target": "es5"
  }

and I'm using next's native support for the baseUrl field. I haven't changed the module or the target.

When I change the _app.tsx imports to:

import { Header } from "../components/Header/Header"
import { Sidebar } from "../components/Sidebar/Sidebar"

the common bundle and app page size drops dramatically, as I would expect it to:

Screenshot 2020-05-06 09 34 21

Expected behavior

The app page size should be the same using both import strategies.

System information

  • OS: [e.g. macOS]
  • Version of Typescript: [e.g. 3.8.3]
  • Version of Next.js: [e.g. 9.3.6]

Metadata

Metadata

Assignees

Labels

TypeScriptRelated to types with Next.js.WebpackRelated to Webpack with Next.js.good first issueEasy to fix issues, good for newcomers

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions