Echarts in Angular
Source: Dev.to
ECharts and Angular Integration Guide
Hey 👋 – Hope you’re having an awesome day!
We’ll discuss how to use ECharts in Angular and achieve proper tree‑shaking through imports. You can either use the ECharts library directly or use the ngx-echarts wrapper.
When to use ECharts Directly vs. ngx-echarts Wrapper
Direct ECharts Usage (No Wrapper)
Pros
- Full control over initialization and lifecycle
- No abstraction layer overhead
- Direct access to all ECharts APIs
Cons
- Manual resize handling required
- More boilerplate code
- You handle memory cleanup directly
ngx-echarts Wrapper
Pros
- Handles Angular lifecycle automatically
- Built‑in resize observer
- Less boilerplate
- Better integration with Angular patterns
Cons
- Additional abstraction layer
- Less control over specific scenarios
- Dependencies on wrapper updates
Recommendation: Use direct ECharts for custom dashboards requiring fine‑grained control; use ngx-echarts for standard applications.
Proper Imports and Tree‑Shaking
❌ Incorrect (Includes Everything)
import * as echarts from 'echarts'; // Bundle: ~700‑900 KB
This imports the entire ECharts library regardless of what you use, resulting in massive bundle sizes.
✅ Correct (Tree‑Shakable)
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
import {
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
// Register only what you use
echarts.use([
BarChart,
LineChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent,
CanvasRenderer
]);
Bundle Size Comparison
- Before (incorrect): ~900 KB
- After (correct): ~80‑100 KB
Savings: 91 % reduction 🚀
Why echarts.use() is Critical
The echarts.use() function registers only the components you need. Without it:
- Larger bundles: Everything gets included
- Slower load times: Users download unnecessary code
- Poor optimization: Tree‑shaking cannot work effectively
Think of it like ordering a whole library when you only need one book.
TypeScript Type Support
To get IDE autocomplete for chart options while maintaining tree‑shaking:
import type { EChartsOption } from 'echarts/types';
const option: EChartsOption = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150],
type: 'line'
}
]
};
Important: Use import type (not just import) to ensure the type is stripped during compilation and doesn’t end up in your bundle.
Happy coding! 🎉