Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
dodov Avatar asked Oct 26 '25 01:10

dodov


1 Answers

This:

import { Foo } from 'my-module'

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

like image 55
dodov Avatar answered Oct 28 '25 16:10

dodov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!