Chart.js Installation
Chart.js provides multiple installation methods suitable for different development scenarios:
- NPM/Yarn - suitable for projects using build tools
- CDN - suitable for rapid prototyping and learning
- GitHub - suitable for developers needing the latest features or wishing to contribute
1. Install via NPM/Yarn
NPM (Node Package Manager) is the package manager for JavaScript, suitable for modern frontend project development.
Installation Steps
# Install using npm
npm install chart.js
# Or use yarn to install
yarn add chart.js
Import into the project
After installation, you can import Chart.js in your JavaScript file like this:
Example
// Import the entire Chart.js library
import
Chart from
'chart.js/auto'
;
// Or import specific chart types on demand (to reduce bundle size)
import
{
Line
}
from
'chart.js'
;
Version Management
To install a specific version of Chart.js, specify the version number:
npm install chart.js@3.9.1
2. Use via CDN
A CDN (Content Delivery Network) loads library files directly over the network and is suitable for rapid prototyping.
Recommended CDN Address
">
Example
Chart.js CDN Example
">
Try it »
This series uses domestic CDN addresses for testing, as in the following example:
Example
3. Get from GitHub
GitHub is a hosting platform for open-source projects, suitable for developers who need the latest features or want to contribute to projects.
How to Obtain
Clone the repository (requires Git):
git clone https://github.com/chartjs/Chart.js.git
Download the ZIP file
- Access the Chart.js GitHub
- Click the "Code" button
- Select "Download ZIP"
Build the project
After downloading, you can build your own version of Chart.js:
cd Chart.js
npm install
npm run build
After the build completes, the generated files can be found in the dist/ directory.
Installation Method Comparison
| Method | Advantages | Disadvantages | Applicable scenarios |
|---|---|---|---|
| NPM/Yarn | Convenient version management, suitable for modern frontend projects | Requires build tools | Formal project development |
| CDN | Simple and fast, no build required | Depends on the network, version updates may be delayed | Rapid prototyping, learning |
| GitHub | Get the latest code, customizable | Requires manual build | Advanced development, contributing code |