dodov
dodov

Reputation: 5844

How to tree-shake exported import?

I have my-module with the following files:

src/components/foo.js

export default class Foo { ... }

src/components/bar.js

export default class Bar { ... }

index.js

import Foo from './src/components/foo'
import Bar from './src/components/bar'

export { Foo, Bar }

My goal is to allow users to easily import both Foo and Bar, but not lose the ability to tree-shake one of them in case only the other one is used.

I tested the following with Webpack:

import { Foo } from 'my-module'

I get Foo, but I get Bar in the resulting bundle as well, which shouldn't happen. The only way to prevent that seems to be by doing this instead:

import Foo from 'my-module/components/foo'

But I don't like this very much since the user needs to know the internal directory structure of the module. Is there a way I can make the former import tree-shakable?

Upvotes: 4

Views: 1566

Answers (1)

dodov
dodov

Reputation: 5844

This:

import { Foo } from 'my-module'

Actually does work correctly and Bar is tree-shaken, but only if Webpack is in production mode.

Upvotes: 2

Related Questions