Skip to content

Instantly share code, notes, and snippets.

@Vlasterx
Last active January 23, 2024 11:31
Show Gist options
  • Save Vlasterx/147830a92d76b521a4e82caeefa96058 to your computer and use it in GitHub Desktop.
Save Vlasterx/147830a92d76b521a4e82caeefa96058 to your computer and use it in GitHub Desktop.
Note for tree shaking

Note for the tree shaking

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'

Enabling tree shaking

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,

Additional Webpack settings

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}`),
      }),
      // ...
    ]
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment