Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly do tree shaking to reduce bundle size and separate entry point for each cloud function

I am using Google Firebase Cloud Functions with TypeScript, and I found out that even though each function is deployed separately, they all share the same bundles and dependencies, even if some functions do not use them nor import them.

In my case, one cloud function uses Redis and others don't. I have 10 functions. All 10 functions actually end up importing redis related code even though they don't import them.

Since all functions share the same entry point, index.js. It currently seems it's impossible to have separate tree-shaken bundles / entry points for each function.

This is very inefficient in terms of bundle size / cold start timing / memory / etc. It also means as I have more and more functions, bundle size will grow for all functions together. It's not scalable.

Is there any way to not share the entry point, index.js, and have completely separate bundles by using bundlers like webpack?

like image 583
Joon Avatar asked Jun 03 '19 07:06

Joon


People also ask

How do you implement tree shaking?

In order to implement tree shaking in react application you will need to have a module bundler that will bundle the entire app's code. You can either use WebPack or RollUp for bundling your application.

What does the term tree shaking mean with regard to JavaScript performance?

Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.


1 Answers

You can create a different local Firebase working area (with firebase init) for each function that should deploy in isolation from the others. You will have to instruct the CLI not to overwrite the other functions on deployment using the --only functions:yourFunctionName to deploy it.

Or, you can deploy function using Cloud tools (gcloud) instead of Firebase tools, but you won't be able to use firebase-functions and its TypeScript bindings.

Or, you can lazily load your modules instead of statically loading them at the global scope of your functions, as described in this video.

I don't recommend using webpack. It's not going to be worth your time to get it configured.

like image 161
Doug Stevenson Avatar answered Sep 22 '22 19:09

Doug Stevenson