This guide shows you how to remove unused API endpoints from an Angular service or API client so that your production bundle only includes the code you actually use. You’ll identify dead endpoints, split your client into smaller injectable services, and configure Angular’s tree shaking to drop the unused ones. This reduces bundle size and improves load time.
What You’ll Need
- An Angular project (version 12 or later recommended) with an existing API client service.
- Angular CLI installed globally or via npx.
- Basic familiarity with TypeScript decorators and Angular dependency injection.
- Access to the codebase where the API client is defined.
Step-by-Step
- Identify unused endpoints. Search your codebase for every method in your API client. Use your IDE’s “Find References” or grep for method names. Note which methods are never called from any component, service, or template. Also check for endpoints called only in dead code (e.g., commented-out sections, unreachable branches).
- List the endpoints to keep. Create a shortlist of methods that are actually used. For each, note which HTTP method and URL it hits. This list will guide the split.
- Split the client into multiple services. Instead of one monolithic service, create separate Angular services grouped by domain or feature. For example, split
UserApiServiceintoUserProfileApiServiceandUserAdminApiService. Move each endpoint method into the appropriate service. Keep the same method signatures and return types to minimize changes in calling code. - Remove unused imports and methods. Delete the methods that are not used anywhere. Also remove any imports that become unused (e.g., models, enums, or helper functions) to avoid leaving dead code that might prevent tree shaking.
- Use Angular’s providedIn for tree shaking. Decorate each new service with
@Injectable({ providedIn: 'root' }). This is the default and allows Angular to tree-shake the service if it’s never injected. Avoid adding services to theprovidersarray of a module unless necessary, because that can prevent tree shaking. - Ensure your build is production-optimized. Run
ng build --prod(orng build --configuration productionin newer versions). This enables tree shaking, minification, and dead code elimination. The Angular compiler will remove services that are not referenced from any entry point. - Verify the bundle size. Use
ng build --stats-jsonand a tool likewebpack-bundle-analyzerto inspect the output. Look for your API client services in the bundle. If an unused service still appears, it means something is referencing it (e.g., an import in a module that is not tree-shaken). - Check for side-effectful imports. If your service file has top-level code that runs on import (like a static property initialization that calls a function), Angular may keep the whole file. Move any such side effects into the constructor or a method, or remove them entirely.
- Update all imports. After splitting, update every file that imported the old monolithic service. Replace with the new specific service imports. Use your IDE’s refactoring tools to do this safely.
- Run your test suite. Run unit tests and any integration tests to ensure nothing broke. If you have tests that mock the API client, update the mocks to match the new service structure.
- Repeat the analysis. After the split, re-run the unused endpoint search. You may find that some endpoints were only used by other unused endpoints, so they can be removed too.
Common Mistakes
- Keeping the service in a module’s providers array. If you add the service to
providersin anNgModule, Angular cannot tree-shake it because the module is a static entry point. UseprovidedIn: 'root'instead. - Leaving unused imports. Even if you delete the method, an unused import of a model or utility can keep a chunk of code alive. Clean up all imports.
- Not checking for indirect references. A service might be used only in a lazy-loaded module that is never loaded. That’s fine, but if it’s referenced in a shared module that is imported eagerly, it will be included. Check the module graph.
- Forgetting to update tests. Tests often import the old service. If they still reference the old class, the build might fail or the old code might be included. Update all test files.
- Assuming tree shaking works with non-exported classes. If your service is not exported from its file, Angular may not be able to analyze it. Always export the service class.
Tips
- Use barrel files sparingly. If you export everything from an index.ts, tree shaking can still work, but it’s easier to import directly from the file path.
- Keep each service focused. A service with 2–5 methods is easier to tree-shake than one with 50.
- Consider using Angular’s
providedInwith a specific route. If an endpoint is only used in a lazy-loaded feature, you can setprovidedIn: 'lazyModule'(if you have a lazy module) to ensure it’s only loaded with that module. - Use the Angular CLI’s build optimizer. It’s enabled by default in production builds and does aggressive dead code elimination.
- Check the bundle with source maps. In production, source maps are off by default, but you can enable them temporarily to see which modules are included.
Troubleshooting
The unused service still appears in the bundle. This usually means something references it. Search for the service name in the entire project, including templates (though templates are compiled to TypeScript). Check for dynamic references like this[serviceName] or injector.get(SomeService). Also check for direct imports in files that are not tree-shaken (e.g., a module that is imported in the root module).
The build fails after splitting. Likely a missing import or a circular dependency. Check the error message. If it’s a circular dependency, you may need to move some shared models to a separate file. Use the Angular CLI’s --verbose flag to get more details.
Tree shaking works but the bundle size didn’t drop. The service might be small, or the unused endpoints might have been already removed by minification. Use the bundle analyzer to see what else is taking space. Also check that your build is truly production (no --dev flags).
Tests fail because they import the old service. Update the imports in your test files. If you have a central mock, update it to provide the new services. If you use HttpClientTestingModule, ensure you provide the new services in the test bed.
The service is used only in a lazy-loaded module, but still included in the main bundle. This can happen if the lazy module is imported eagerly somewhere, or if the service is provided in a shared module that is imported in the root. Move the service to the lazy module’s own providers array (but then it won’t be tree-shaken if the module is never loaded, which is fine).
Frequently Asked Questions
Q: Does Angular tree shake services by default?
A: Yes, if you use providedIn: 'root' and the service is not referenced from any entry point, Angular’s production build will remove it.
Q: Can I tree shake a service that uses the HttpClient?
A: Yes, the HttpClient is itself tree-shakable. As long as your service is not referenced, it will be removed, and the HttpClient code will only be included if something else uses it.
Q: What if I have a base class with common methods?
A: That’s fine. The base class will be tree-shaken if no subclass is used. But if you have a base class with many methods and only one subclass uses one method, the whole base class might be included. Consider using composition instead.
Q: Do I need to use the Angular CLI for tree shaking?
A: No, you can use any build system that supports tree shaking (like webpack with the Angular compiler). But the Angular CLI is the easiest because it’s pre-configured.
Q: Will tree shaking break lazy loading?
A: No, tree shaking works with lazy loading. In fact, it’s complementary. Lazy loading splits your bundle, and tree shaking removes unused code from each chunk.
Q: How do I know if tree shaking is working?
A: Use the bundle analyzer. If you remove a service and the bundle size decreases, tree shaking is working. You can also inspect the minified code for the service name.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Upgrade MTG Foundations Commander Deck on a Budget
- Cardano Bridge Frozen Withdrawals: What to Do
- Smoke Alarm Alerts via HomePod: Setup Guide
- Anti-Aliasing Explained: What It Is and How It Works
- Highlight Above & Below Average Values in Excel
- Conveyor Belt Design Calculations Explained