阿里云主机折上折
  • 微信号
Current Site:Index > On-demand importing and bundle optimization

On-demand importing and bundle optimization

Author:Chuan Chen 阅读数:25473人阅读 分类: ECharts

The Necessity of On-Demand Import

ECharts, as a powerful data visualization library, has a relatively large full package size (approximately 700KB when compressed). In actual projects, especially in mobile or performance-sensitive scenarios, importing the full package leads to resource waste. Through on-demand importing, developers can load only the chart types and components they use, significantly reducing the bundle size.

// Full import (not recommended)
import * as echarts from 'echarts';

// On-demand import (recommended approach)
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([BarChart, GridComponent, CanvasRenderer]);

Core Module Division

ECharts 5+ adopts a modular architecture, primarily divided into four core modules:

  1. Core Module (echarts/core): Contains basic coordinate systems, animation systems, etc.
  2. Chart Module (echarts/charts): Various chart types such as line charts, pie charts, etc.
  3. Component Module (echarts/components): Toolbox, legend, tooltip, etc.
  4. Renderer Module (echarts/renderers): Canvas or SVG renderers.
// Typical modules required for a line chart
import {
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components';

Custom Bundling Solutions

Further optimization can be achieved through Webpack's externals configuration:

// webpack.config.js
module.exports = {
  externals: {
    echarts: 'echarts'
  }
}

Combined with CDN for core file import:

<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

Tree Shaking Practices

Modern bundlers support Tree Shaking but require ES module specifications:

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', { modules: false }]
  ]
}

Alongside the sideEffects declaration in package.json:

{
  "sideEffects": ["*.css", "*.scss"]
}

Lazy Loading Strategy

For large dashboard projects, dynamic imports can be used:

// Dynamically load map data
const loadMap = async (mapName) => {
  const { default: mapJson } = await import(`echarts/map/json/${mapName}.json`);
  echarts.registerMap(mapName, mapJson);
};

Component-Level Optimization

For Vue/React projects, lightweight encapsulation is recommended:

// React component example
import React, { useEffect, useRef } from 'react';
import initECharts from './initECharts'; // Custom initialization logic

function EChart({ option }) {
  const chartRef = useRef(null);
  
  useEffect(() => {
    const chart = initECharts(chartRef.current);
    chart.setOption(option);
    return () => chart.dispose();
  }, [option]);

  return <div ref={chartRef} style={{ width: '100%', height: '400px' }} />;
}

Bundle Analysis Tools

Use webpack-bundle-analyzer to analyze dependencies:

npm install --save-dev webpack-bundle-analyzer

Configure the plugin:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

On-Demand Theme Loading

ECharts theme files can also be loaded on demand:

// Dynamically load a theme
import('echarts/theme/dark').then(theme => {
  echarts.registerTheme('myDark', theme);
  chart.setOption({ theme: 'myDark' });
});

Extension Plugin Management

For extensions like watermark or rich text plugins:

// Import only when needed
import 'echarts-liquidfill/src/liquidFill.js';
import 'echarts-wordcloud/src/wordCloud.js';

Server-Side Rendering Optimization

Special handling is required for SSR scenarios:

// Check the runtime environment
const canUseDOM = typeof window !== 'undefined';
const echarts = canUseDOM ? require('echarts') : null;

Version Locking Strategy

Avoid accidentally importing multiple versions:

{
  "resolutions": {
    "echarts": "5.4.3"
  }
}

Performance Monitoring Solution

Implement runtime bundle size monitoring:

function getModuleSize() {
  const modules = Object.keys(require.cache)
    .filter(key => key.includes('echarts'));
  return modules.reduce((total, module) => {
    return total + require.cache[module].size;
  }, 0);
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.