DEV Community

Varad Shirsath
Varad Shirsath

Posted on

Echarts in Angular

ECharts and Angular Integration Guide

Hey👋- Hope you're having an awesome day!

So, we are going to discuss how to use the echarts in angular and how to achieve the proper tree-shaking through imports. We can either directly use the echarts library or we can 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
Enter fullscreen mode Exit fullscreen mode

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
]);
Enter fullscreen mode Exit fullscreen mode

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:

  1. Larger bundles: Everything gets included
  2. Slower load times: Users download unnecessary code
  3. 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'
    }
  ]
};
Enter fullscreen mode Exit fullscreen mode

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! 🎉

Top comments (0)