D3.js 安装与配置 #

安装方式概览 #

D3.js 提供多种安装方式,适应不同的项目需求:

text
┌─────────────────────────────────────────────────────────────┐
│                    D3.js 安装方式                            │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │    CDN      │  │    NPM      │  │   下载文件   │         │
│  │  最简单      │  │  推荐        │  │   离线使用   │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
│  ┌─────────────┐  ┌─────────────┐                          │
│  │   模块化     │  │   构建工具   │                          │
│  │  按需加载    │  │  Webpack等   │                          │
│  └─────────────┘  └─────────────┘                          │
└─────────────────────────────────────────────────────────────┘

方式一:CDN 引入(最简单) #

适合快速原型开发和学习。

完整版 #

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>D3.js Demo</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <div id="chart"></div>
  <script>
    d3.select('#chart')
      .append('svg')
      .attr('width', 500)
      .attr('height', 300);
  </script>
</body>
</html>

CDN 选项 #

html
<script src="https://d3js.org/d3.v7.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>

<script src="https://unpkg.com/d3@7"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>

开发版(带调试信息) #

html
<script src="https://d3js.org/d3.v7.js"></script>

方式二:NPM 安装(推荐) #

适合正式项目开发,支持模块化。

安装 D3.js #

bash
npm install d3

安装特定版本 #

bash
npm install d3@7
npm install d3@7.8.5

完整导入 #

javascript
import * as d3 from 'd3';

const svg = d3.select('#chart')
  .append('svg')
  .attr('width', 500)
  .attr('height', 300);

按需导入(推荐) #

javascript
import { select, scaleLinear } from 'd3';

const svg = select('#chart')
  .append('svg');

const xScale = scaleLinear()
  .domain([0, 100])
  .range([0, 500]);

方式三:模块化安装 #

只安装需要的模块,减小打包体积。

安装特定模块 #

bash
npm install d3-selection
npm install d3-scale
npm install d3-axis
npm install d3-shape
npm install d3-transition

导入模块 #

javascript
import { select, selectAll } from 'd3-selection';
import { scaleLinear, scaleBand } from 'd3-scale';
import { axisBottom, axisLeft } from 'd3-axis';
import { line, area } from 'd3-shape';
import { transition } from 'd3-transition';

const svg = select('#chart').append('svg');

常用模块列表 #

模块 功能 导入示例
d3-selection 选择器 import { select } from 'd3-selection'
d3-scale 比例尺 import { scaleLinear } from 'd3-scale'
d3-axis 坐标轴 import { axisBottom } from 'd3-axis'
d3-shape 形状 import { line } from 'd3-shape'
d3-transition 过渡 import { transition } from 'd3-transition'
d3-ease 缓动 import { easeLinear } from 'd3-ease'
d3-force 力导向 import { forceSimulation } from 'd3-force'
d3-geo 地理 import { geoPath } from 'd3-geo'
d3-hierarchy 层次 import { tree } from 'd3-hierarchy'
d3-dsv 数据解析 import { csv } from 'd3-dsv'
d3-fetch 数据获取 import { csv } from 'd3-fetch'
d3-time 时间 import { timeDay } from 'd3-time'
d3-format 格式化 import { format } from 'd3-format'
d3-array 数组 import { max, min } from 'd3-array'

方式四:下载文件 #

适合离线开发或特殊部署需求。

下载地址 #

text
完整版(压缩):
https://d3js.org/d3.v7.min.js

完整版(未压缩):
https://d3js.org/d3.v7.js

特定版本:
https://github.com/d3/d3/releases

本地引用 #

html
<script src="./lib/d3.min.js"></script>

开发环境配置 #

VS Code 配置 #

推荐安装以下扩展:

text
1. Live Server - 本地开发服务器
2. SVG Preview - SVG 预览
3. Prettier - 代码格式化
4. ESLint - 代码检查

项目结构 #

text
my-d3-project/
├── index.html
├── css/
│   └── style.css
├── js/
│   └── main.js
├── data/
│   └── data.csv
└── lib/
    └── d3.min.js

基础 HTML 模板 #

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>D3.js 项目</title>
  <style>
    body {
      margin: 0;
      padding: 20px;
      font-family: Arial, sans-serif;
    }
    #chart {
      width: 800px;
      height: 500px;
    }
  </style>
</head>
<body>
  <div id="chart"></div>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <script src="./js/main.js"></script>
</body>
</html>

构建工具配置 #

Webpack 配置 #

javascript
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

Vite 配置 #

javascript
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          d3: ['d3']
        }
      }
    }
  }
});

Rollup 配置 #

javascript
import resolve from '@rollup/plugin-node-resolve';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'umd',
    globals: {
      d3: 'd3'
    }
  },
  plugins: [resolve()]
};

TypeScript 支持 #

D3.js 内置 TypeScript 类型定义。

安装 #

bash
npm install d3
npm install --save-dev typescript

tsconfig.json #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

TypeScript 使用示例 #

typescript
import * as d3 from 'd3';

interface DataPoint {
  x: number;
  y: number;
}

const data: DataPoint[] = [
  { x: 0, y: 10 },
  { x: 1, y: 20 },
  { x: 2, y: 15 }
];

const xScale = d3.scaleLinear()
  .domain([0, d3.max(data, d => d.x) ?? 0])
  .range([0, 500]);

const svg = d3.select<SVGSVGElement, unknown>('#chart')
  .append('svg')
  .attr('width', 500)
  .attr('height', 300);

React 集成 #

安装 #

bash
npm install d3
npm install react react-dom

React 组件示例 #

jsx
import React, { useRef, useEffect } from 'react';
import * as d3 from 'd3';

const BarChart = ({ data }) => {
  const svgRef = useRef(null);

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    
    const width = 500;
    const height = 300;
    const margin = { top: 20, right: 20, bottom: 30, left: 40 };
    
    const xScale = d3.scaleBand()
      .domain(data.map(d => d.label))
      .range([margin.left, width - margin.right])
      .padding(0.1);
    
    const yScale = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)])
      .range([height - margin.bottom, margin.top]);
    
    svg.selectAll('.bar')
      .data(data)
      .join('rect')
      .attr('class', 'bar')
      .attr('x', d => xScale(d.label))
      .attr('y', d => yScale(d.value))
      .attr('width', xScale.bandwidth())
      .attr('height', d => height - margin.bottom - yScale(d.value))
      .attr('fill', 'steelblue');
  }, [data]);

  return (
    <svg
      ref={svgRef}
      width={500}
      height={300}
    />
  );
};

export default BarChart;

Vue 集成 #

安装 #

bash
npm install d3
npm install vue

Vue 组件示例 #

vue
<template>
  <svg ref="svgRef" :width="width" :height="height"></svg>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as d3 from 'd3';

const props = defineProps({
  data: Array,
  width: { type: Number, default: 500 },
  height: { type: Number, default: 300 }
});

const svgRef = ref(null);

const drawChart = () => {
  const svg = d3.select(svgRef.value);
  const margin = { top: 20, right: 20, bottom: 30, left: 40 };
  
  const xScale = d3.scaleBand()
    .domain(props.data.map(d => d.label))
    .range([margin.left, props.width - margin.right])
    .padding(0.1);
  
  const yScale = d3.scaleLinear()
    .domain([0, d3.max(props.data, d => d.value)])
    .range([props.height - margin.bottom, margin.top]);
  
  svg.selectAll('.bar')
    .data(props.data)
    .join('rect')
    .attr('class', 'bar')
    .attr('x', d => xScale(d.label))
    .attr('y', d => yScale(d.value))
    .attr('width', xScale.bandwidth())
    .attr('height', d => props.height - margin.bottom - yScale(d.value))
    .attr('fill', 'steelblue');
};

onMounted(drawChart);
watch(() => props.data, drawChart, { deep: true });
</script>

开发工具 #

浏览器开发者工具 #

text
1. Chrome DevTools
   - Elements 面板:查看 DOM 结构
   - Console 面板:调试 D3 代码
   - Sources 面板:设置断点

2. Firefox Developer Tools
   - SVG 检查器
   - 动画检查器

调试技巧 #

javascript
console.log(d3.select('#chart').node());

d3.selectAll('circle').each(function(d, i) {
  console.log(i, d, this);
});

d3.select('svg').append('rect')
  .attr('debug', 'true')
  .each(function() {
    console.log('Element created:', this);
  });

常见问题 #

1. 版本兼容性 #

javascript
// D3 v7 使用 ES 模块
import * as d3 from 'd3';

// D3 v5/v6 可以使用 require
const d3 = require('d3');

2. 模块导入问题 #

javascript
// 错误:transition 需要显式导入
import { select } from 'd3-selection';
select('svg').transition(); // 报错

// 正确:同时导入 transition
import { select } from 'd3-selection';
import 'd3-transition';
select('svg').transition();

3. CDN 加载失败 #

html
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
  if (typeof d3 === 'undefined') {
    console.error('D3.js 加载失败');
  }
</script>

版本选择建议 #

场景 推荐版本 说明
新项目 D3 v7 最新特性,ES 模块
维护旧项目 D3 v5/v6 兼容性考虑
学习入门 D3 v7 最新文档和示例
IE 支持 D3 v4 需要 polyfill

下一步 #

现在你已经安装并配置好 D3.js,接下来学习 选择器,开始操作 DOM 元素!

最后更新:2026-03-28