Search code examples
angulartree-shakingnrwl-nx

Angular does not tree shake nx lib which contains client (angular) and server code


I am using a nrwl nx workspace. I have a workspace library (libs/jobs) that holds all the logic of my "job" module. It contains server side code as well as an angular module. The angular module has no dependencies to the server code but if I load the module via import('@reporting/jobs').then(m => m.JobsClientModule) it fails because it can't find node apis like fs while compiling.

I thought tree shaking would eliminate the unused server code. Why doesn't it?

My current workaround is to add a new entry to tsconfig.json --> path: "@reporting/jobs-client": ["libs/jobs/src/client/index.ts"]. Which imports only the client stuff from the module. But this feels pretty hacky :(

Any suggestions how to create a lib / module containing all the code (server & client) for one feature?


Solution

  • Angular uses webpacks bundle loader which in turn uses the native dynamic imports.

    WebPack will find all import('') and create entry points for them. So I don't think there is a way for angular to magically fix this.

    The way you have done it is fine, but you will miss out on being able to use nx tags to enforce rules.

    What I have done in our repo is split the modules that have both client and server code into multiple libs.

    Something like this:

    // contains the business logic / interfaces that can be used both client and server side. (cannot contain any node imports)
    @reporting/jobs/domain
    
    // the angular feature module that contains routing and can be lazy loaded via loadChildren
    @reporting/jobs/feature-job-dashboard
    
    // the cloud function that gets invoked by cloud scheduler
    @reporting/jobs/backend-scheduled-import
    
    

    I find strongly separating backend and frontend implementation details makes it easier to grasp what gets run where, and results in cleaner, easier to test code. but it is quite hard choosing when to create new libs.

    Good luck :)