Chart.js 安装与配置 #
安装方式概览 #
Chart.js 提供了多种安装方式,适用于不同的项目场景:
text
┌─────────────────────────────────────────────────────────────┐
│ Chart.js 安装方式 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ CDN │ │ npm │ │ 下载文件 │ │
│ │ 快速测试 │ │ 项目开发 │ │ 离线使用 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ yarn │ │ pnpm │ │
│ │ 包管理器 │ │ 包管理器 │ │
│ └─────────────┘ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
方式一:CDN 引入 #
直接引入(最简单) #
适合快速测试和学习:
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js 示例</title>
</head>
<body>
<canvas id="myChart"></canvas>
<!-- 从 CDN 引入 Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: '示例数据',
data: [12, 19, 3]
}]
}
});
</script>
</body>
</html>
CDN 选项 #
| CDN | URL | 特点 |
|---|---|---|
| jsDelivr | https://cdn.jsdelivr.net/npm/chart.js |
全球加速,国内友好 |
| unpkg | https://unpkg.com/chart.js |
自动使用最新版本 |
| cdnjs | https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js |
稳定可靠 |
指定版本 #
html
<!-- 指定版本号 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<!-- 使用最新版本 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@latest"></script>
方式二:npm 安装 #
初始化项目 #
bash
# 创建项目目录
mkdir my-chart-project
cd my-chart-project
# 初始化 npm 项目
npm init -y
安装 Chart.js #
bash
# 安装最新版本
npm install chart.js
# 安装指定版本
npm install chart.js@4.4.1
# 安装开发版本
npm install chart.js@next
项目结构 #
text
my-chart-project/
├── node_modules/
│ └── chart.js/
├── src/
│ ├── index.js
│ └── charts/
│ ├── bar.js
│ └── line.js
├── index.html
├── package.json
└── package-lock.json
使用方式 #
javascript
// src/index.js
import Chart from 'chart.js/auto';
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'line',
data: {
labels: ['一月', '二月', '三月', '四月', '五月'],
datasets: [{
label: '月度数据',
data: [65, 59, 80, 81, 56],
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
}
});
方式三:yarn 安装 #
bash
# 安装 yarn(如果未安装)
npm install -g yarn
# 创建项目
yarn init -y
# 安装 Chart.js
yarn add chart.js
# 安装指定版本
yarn add chart.js@4.4.1
方式四:pnpm 安装 #
bash
# 安装 pnpm(如果未安装)
npm install -g pnpm
# 创建项目
pnpm init
# 安装 Chart.js
pnpm add chart.js
方式五:下载文件 #
下载地址 #
从 GitHub Releases 下载:
text
https://github.com/chartjs/Chart.js/releases
文件说明 #
text
chart.js/
├── chart.js - UMD 版本(开发)
├── chart.min.js - UMD 版本(生产)
├── chart.umd.js - UMD 模块
└── chart.umd.min.js - UMD 模块(压缩)
本地引用 #
html
<script src="./path/to/chart.umd.min.js"></script>
模块化导入 #
ES Modules(推荐) #
javascript
// 导入所有图表类型
import Chart from 'chart.js/auto';
// 按需导入(Tree-shaking 优化)
import {
Chart,
BarController,
LineController,
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
Title,
Tooltip,
Legend
} from 'chart.js';
// 注册需要的组件
Chart.register(
BarController,
LineController,
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
Title,
Tooltip,
Legend
);
CommonJS #
javascript
const Chart = require('chart.js/auto');
// 或者
const { Chart } = require('chart.js');
AMD #
javascript
require(['chart.js'], function(Chart) {
const ctx = document.getElementById('myChart');
new Chart(ctx, config);
});
TypeScript 支持 #
Chart.js 4.x 内置 TypeScript 类型定义:
typescript
// 安装(如果类型未包含)
npm install --save-dev @types/chart.js
// 使用
import Chart, { ChartConfiguration, ChartType } from 'chart.js/auto';
const config: ChartConfiguration = {
type: 'bar' as ChartType,
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: '数据',
data: [1, 2, 3]
}]
}
};
const chart = new Chart(ctx, config);
构建工具配置 #
Vite #
javascript
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rollupOptions: {
output: {
manualChunks: {
'chart.js': ['chart.js']
}
}
}
}
});
javascript
// main.js
import Chart from 'chart.js/auto';
const ctx = document.getElementById('myChart');
new Chart(ctx, config);
Webpack #
javascript
// webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
}
};
Rollup #
javascript
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'umd'
},
plugins: [
resolve(),
commonjs()
]
};
框架集成 #
React #
bash
# 安装
npm install chart.js react-chartjs-2
jsx
// App.jsx
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
import { Bar } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
function App() {
const data = {
labels: ['一月', '二月', '三月'],
datasets: [{
label: '销售额',
data: [12, 19, 3],
backgroundColor: 'rgba(75, 192, 192, 0.5)'
}]
};
const options = {
responsive: true,
plugins: {
title: {
display: true,
text: '销售数据'
}
}
};
return <Bar data={data} options={options} />;
}
Vue 3 #
bash
# 安装
npm install chart.js vue-chartjs
vue
<!-- BarChart.vue -->
<template>
<Bar :data="chartData" :options="chartOptions" />
</template>
<script setup>
import { Bar } from 'vue-chartjs';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);
const chartData = {
labels: ['一月', '二月', '三月'],
datasets: [{
label: '销售额',
data: [12, 19, 3],
backgroundColor: 'rgba(75, 192, 192, 0.5)'
}]
};
const chartOptions = {
responsive: true
};
</script>
Angular #
bash
# 安装
npm install chart.js ng2-charts
typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { NgChartsModule } from 'ng2-charts';
@NgModule({
imports: [NgChartsModule]
})
export class AppModule {}
html
<!-- app.component.html -->
<canvas baseChart
[data]="barChartData"
[options]="barChartOptions"
[type]="'bar'">
</canvas>
typescript
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
barChartData = {
labels: ['一月', '二月', '三月'],
datasets: [{
label: '销售额',
data: [12, 19, 3]
}]
};
barChartOptions = {
responsive: true
};
}
Svelte #
bash
# 安装
npm install chart.js svelte-chartjs
svelte
<!-- BarChart.svelte -->
<script>
import { Bar } from 'svelte-chartjs';
const data = {
labels: ['一月', '二月', '三月'],
datasets: [{
label: '销售额',
data: [12, 19, 3]
}]
};
const options = {
responsive: true
};
</script>
<Bar {data} {options} />
开发工具 #
VS Code 扩展 #
推荐安装以下扩展:
- Chart.js IntelliSense - Chart.js 代码提示
- ES6 code snippets - ES6 代码片段
- Prettier - 代码格式化
浏览器扩展 #
- React Developer Tools - React 调试
- Vue DevTools - Vue 调试
在线编辑器 #
环境验证 #
验证安装 #
html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="testChart"></canvas>
<script>
// 验证 Chart.js 是否加载成功
if (typeof Chart !== 'undefined') {
console.log('Chart.js 版本:', Chart.version);
// 创建测试图表
const ctx = document.getElementById('testChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['测试'],
datasets: [{
label: '验证',
data: [1]
}]
}
});
console.log('Chart.js 安装成功!');
} else {
console.error('Chart.js 加载失败!');
}
</script>
</body>
</html>
控制台检查 #
javascript
// 检查版本
console.log(Chart.version);
// 检查已注册的控制器
console.log(Chart.controllers);
// 检查已注册的插件
console.log(Chart.plugins);
常见问题 #
1. CDN 加载失败 #
html
<!-- 使用备用 CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
if (typeof Chart === 'undefined') {
// 加载备用 CDN
var script = document.createElement('script');
script.src = 'https://unpkg.com/chart.js';
document.head.appendChild(script);
}
</script>
2. 模块导入错误 #
javascript
// 错误:import Chart from 'chart.js'
// 正确:
import Chart from 'chart.js/auto';
// 或者按需导入
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
3. TypeScript 类型问题 #
typescript
// 确保安装了类型定义
// npm install --save-dev @types/chart.js
// 使用正确的类型导入
import type { ChartConfiguration } from 'chart.js';
4. Canvas 未找到 #
javascript
// 确保 DOM 加载完成
document.addEventListener('DOMContentLoaded', function() {
const ctx = document.getElementById('myChart');
if (ctx) {
new Chart(ctx, config);
} else {
console.error('Canvas 元素未找到');
}
});
最佳实践 #
1. 使用 Tree-shaking #
javascript
// 只导入需要的组件
import {
Chart,
BarController,
CategoryScale,
LinearScale
} from 'chart.js';
Chart.register(BarController, CategoryScale, LinearScale);
2. 版本锁定 #
json
// package.json
{
"dependencies": {
"chart.js": "4.4.1"
}
}
3. 环境区分 #
javascript
// 开发环境
const config = {
...baseConfig,
animation: {
duration: 1000
}
};
// 生产环境
const config = {
...baseConfig,
animation: {
duration: 0
}
};
下一步 #
环境搭建完成后,接下来学习 基础使用,创建你的第一个图表!
最后更新:2026-03-28