Skip to content

HighCharts - 环境设置

在你的 Web 项目中设置 Highcharts 非常简单。Highcharts 是一个独立的 JavaScript 库,这意味着它不再需要 jQuery 或任何其他外部框架即可运行。

你可以通过以下几种方法将 Highcharts 引入到你的项目中:

内容分发网络(CDN)是开始使用的最快方式。Highcharts 将其文件托管在全球分布的服务器上,确保你的用户加载速度快。

将 Highcharts 主脚本文件包含在 HTML 文件的 <head> 或 </body> 结束标签之前:

<!-- 始终检查 code.highcharts.com 获取最新版本 -->
<script src="https://code.highcharts.com/highcharts.js"></script>

许多功能,例如导出、可访问性增强或特定图表类型(例如,热力图、树状图),都作为单独的模块提供。将它们包含在核心库之后:

<!-- 示例:添加导出和可访问性模块 -->
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<!-- 示例:添加特定图表类型模块 -->
<script src="https://code.highcharts.com/modules/heatmap.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Highcharts CDN Example</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
</head>
<body>
<div id="container" style="width:100%; height:400px;"></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
const chart = Highcharts.chart('container', {
// Your Highcharts configuration object goes here
chart: {
type: 'bar' // Example chart type
},
title: {
text: 'My First Highchart'
}, series: [{
name: 'Example Series',
data: [1, 3, 2, 4]
}]
});
});
</script>
</body>
</html>

方法 2: 使用 NPM 或 Yarn (适用于模块打包器)

Section titled “方法 2: 使用 NPM 或 Yarn (适用于模块打包器)”

如果你在使用 Webpack、Rollup 或 Parcel 等构建工具,通过包管理器安装 Highcharts 是推荐的方法。

在你的项目目录下打开终端并运行:

# Using npm
npm install highcharts
# Using yarn
yarn add highcharts

在你的 JavaScript 或 TypeScript 文件中,导入 Highcharts 库并初始化所有必需的模块:

// Import Highcharts core library
import Highcharts from 'highcharts';
// Import optional modules
import Exporting from 'highcharts/modules/exporting';
import Accessibility from 'highcharts/modules/accessibility';
import Heatmap from 'highcharts/modules/heatmap'; // Example chart type module
// Initialize the modules
Exporting(Highcharts);
Accessibility(Highcharts);
Heatmap(Highcharts); // Initialize chart type modules too
// Find your container element (assuming you have <div id="container"></div> in your HTML)
const container = document.getElementById('container');
// Check if the container exists before creating the chart
if (container) {
// Create the chart
const chart = Highcharts.chart(container, {
// Your Highcharts configuration object goes here
chart: {
type: 'heatmap' // Example chart type
},
title: {
text: 'Highcharts NPM Example'
},
// ... other configuration options
series: [ /* ... series data ... */ ]
});
} else {
console.error('Chart container #container not found.');
}

Highcharts 还提供了针对 React、Angular 和 Vue 等流行框架的官方包装器,简化了集成。请查阅 Highcharts 官方文档,了解适用于你的框架的具体说明。

选择最适合你的项目结构和开发流程的方法。