阿里云主机折上折
  • 微信号
Current Site:Index > npm installation and modular usage

npm installation and modular usage

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

npm Installation and Modular Usage

ECharts, as a powerful data visualization library, can be installed and managed via npm. This approach not only facilitates version control but also integrates better with modern front-end engineering tools.

npm Installation of ECharts

The simplest way to install ECharts is via the npm command:

npm install echarts --save

This will install the latest stable version of ECharts into your project. To install a specific version, specify the version number:

npm install echarts@5.4.3 --save

For projects sensitive to size, consider on-demand importing:

npm install echarts --save
npm install @echarts/core --save

Modular Import Methods

In modern front-end projects, there are typically the following import methods:

  1. Full Import (suitable for rapid development):
import * as echarts from 'echarts';
  1. On-Demand Import (recommended for production environments):
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]);
  1. Theme Import:
import 'echarts/theme/dark';

Basic Usage Example

Here is a complete ECharts usage example:

// Import ECharts
import * as echarts from 'echarts';

// Initialize the chart
const chartDom = document.getElementById('main');
const myChart = echarts.init(chartDom);

// Configuration options
const option = {
  title: {
    text: 'ECharts Getting Started Example'
  },
  tooltip: {},
  legend: {
    data: ['Sales']
  },
  xAxis: {
    data: ['Shirts', 'Wool Sweaters', 'Chiffon Shirts', 'Pants', 'High Heels', 'Socks']
  },
  yAxis: {},
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
};

// Display the chart using the configuration
myChart.setOption(option);

Advanced Modular Techniques

For large projects, chart configurations and logic can be separated:

  1. Configuration Separation:
// config/chartOptions.js
export const barOption = {
  // Bar chart configuration
};

export const lineOption = {
  // Line chart configuration
};
  1. Custom Themes:
// theme/customTheme.js
export const customTheme = {
  color: ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae'],
  // Other theme configurations
};
  1. Chart Component Encapsulation:
// components/BaseChart.vue
<template>
  <div ref="chart" style="width: 100%; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  props: ['option'],
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.chart.setOption(this.option);
      
      window.addEventListener('resize', this.resizeHandler);
    },
    resizeHandler() {
      this.chart && this.chart.resize();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
    this.chart && this.chart.dispose();
  }
};
</script>

Common Issue Resolution

  1. Chart Not Displaying:
  • Ensure the DOM container has explicit width and height
  • Check if the setOption method was called
  • Look for errors in the console
  1. On-Demand Import Errors:
// Errors occur when necessary components are missing
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
// Must import necessary components
import { GridComponent, TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([BarChart, GridComponent, TooltipComponent, CanvasRenderer]);
  1. Performance Optimization:
// Use incremental rendering for large datasets
option = {
  series: [{
    type: 'line',
    progressive: 1000,  // Incremental rendering threshold
    data: largeData
  }]
};

Integration with Other Tools

  1. Integration with Vue:
// Vue 3 Example
import { onMounted, onBeforeUnmount, ref } from 'vue';
import * as echarts from 'echarts';

export default {
  setup() {
    const chartRef = ref(null);
    let chartInstance = null;
    
    onMounted(() => {
      chartInstance = echarts.init(chartRef.value);
      chartInstance.setOption({
        /* Configuration options */
      });
    });
    
    onBeforeUnmount(() => {
      chartInstance && chartInstance.dispose();
    });
    
    return { chartRef };
  }
};
  1. Integration with React:
// React Example
import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

function EChartComponent({ option }) {
  const chartRef = useRef(null);
  
  useEffect(() => {
    const chart = echarts.init(chartRef.current);
    chart.setOption(option);
    
    const resizeHandler = () => chart.resize();
    window.addEventListener('resize', resizeHandler);
    
    return () => {
      window.removeEventListener('resize', resizeHandler);
      chart.dispose();
    };
  }, [option]);
  
  return <div ref={chartRef} style={{ width: '100%', height: '400px' }} />;
}

Version Management and Upgrades

  1. Check Current Version:
console.log(echarts.version);
  1. Upgrade ECharts:
npm update echarts
  1. Version Difference Handling:
// Compatibility handling from v4 to v5
if (typeof echarts.registerMap === 'function') {
  // v5 handling
} else {
  // v4 handling
}

Custom Extensions

ECharts supports custom series and components:

// Custom series example
echarts.registerChartType('customSeries', function(params) {
  return {
    // Custom rendering logic
  };
});

// Using custom series
option = {
  series: [{
    type: 'customSeries',
    // Other configurations
  }]
};

Server-Side Rendering

ECharts also supports server-side rendering in Node.js environments:

const echarts = require('echarts');
const { createCanvas } = require('canvas');

// Create canvas
const canvas = createCanvas(800, 600);
echarts.setCanvasCreator(() => canvas);

// Generate chart
const chart = echarts.init(canvas);
chart.setOption(/* Configuration options */);

// Get image buffer
const buffer = canvas.toBuffer('image/png');

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.