In order to properly enable tree shaking, each main function whould be written in its own file, exported as default
and then additionally exported from the index.ts
.
/src/something/some-function.ts
export const someFunction = () => {}
export default someFunction
/src/index.ts
export { default as someFunction } from './src/something/some-function.ts'
Then you can import in another web package it as you would with any named export
import { someFunction } from 'some-package'
To enable tree shaking, following steps should be taken as well:
- Webpack will enable tree shaking if the build is set to
production
mode. - Babel should posses the following
"presets": [ ["@babel/preset-env", { "modules": false }] ],
package.json
for the library package file should have"sideEffects": false,
If you are using monorepo, Webpack should exclude all packages that are not intended for the front-end usage, or are not a part of the currently built web app.
- Create a list of excluded packages
const ignorePackages = [
'package1',
'package2',
//...
].join('|')
- Add that list to ignore plugin in webpack config
// ...
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: new RegExp(`${ignorePackages}`),
}),
// ...
]
// ...