To create a chart in a TypeScript application, you'll likely want to use a charting library. One of the most popular and powerful charting libraries for JavaScript (and TypeScript) is Chart.js.
Set up your TypeScript Project
If you don't have a TypeScript project set up yet, you can create a new one.
Initialize a new npm project.
npm init -y
Install TypeScript.
npm install typescript --save-dev
Install Chart.js.
npm install chart.js --save
Install TypeScript types for Chart.js.
npm install @types/chart.js --save-dev
Create the TypeScript Code for the Chart
- Create a src folder and inside it, create a chart.ts file (or whatever you want to name it).
- In chart.ts, write the following code.
import { Chart, ChartConfiguration, ChartData, ChartOptions } from 'chart.js/auto';
class ChartManager {
private chart: Chart | null = null;
constructor() {
this.initializeChart();
}
private initializeChart(): void {
// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', () => {
this.createChart();
});
}
private createChart(): void {
// Get the canvas element
const canvas = document.getElementById('myChart') as HTMLCanvasElement;
if (!canvas) {
console.error('Canvas element not found');
return;
}
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('Could not get 2D context');
return;
}
const data: ChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
};
const options: ChartOptions = {
responsive: true,
plugins: {
title: {
display: true,
text: 'Monthly Data Visualization'
},
legend: {
display: true,
position: 'top'
},
tooltip: {
enabled: true
}
},
scales: {
y: {
beginAtZero: true,
grid: {
display: true
}
},
x: {
grid: {
display: false
}
}
}
};
const config: ChartConfiguration = {
type: 'bar',
data: data,
options: options
};
this.chart = new Chart(ctx, config);
}
public updateData(newData: number[]): void {
if (this.chart) {
this.chart.data.datasets[0].data = newData;
this.chart.update();
}
}
public destroy(): void {
if (this.chart) {
this.chart.destroy();
this.chart = null;
}
}
}
const chartManager = new ChartManager();
export default chartManager;
Create the HTML File
In the root of your project, create an index.html file to include the canvas element and the bundled JavaScript file (once the TypeScript is compiled).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chart.js with TypeScript</title>
<style>
.chart-container {
width: 80%;
max-width: 800px;
margin: 2rem auto;
padding: 1rem;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>
<script src="dist/bundle.js"></script>
</body>
</html>
Compile TypeScript and Bundle with Webpack (Optional)
If you're using TypeScript with Webpack, you will need to configure it to transpile and bundle the TypeScript code into a single JavaScript file.
Install Webpack and Webpack CLI.
npm install webpack webpack-cli --save-dev
Install a TypeScript loader for Webpack.
npm install ts-loader --save-dev
Create a webpack.config.js file at the root of your project.
const path = require('path');
module.exports = {
entry: './src/chart.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
devtool: 'source-map',
devServer: {
static: {
directory: path.join(__dirname, '/'),
},
compress: true,
port: 9000,
},
};
Create a tsconfig.json file for TypeScript.
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
{
"dependencies": {
"chart.js": "^4.4.1"
},
"devDependencies": {
"typescript": "^5.3.3",
"ts-loader": "^9.5.1",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"@types/chart.js": "^2.9.41"
},
"scripts": {
"start": "webpack serve --open",
"build": "webpack"
}
}
Add build scripts to package.json as above. Now Build the TypeScript code and bundle it using Webpack.
npm run build
Create the file structure
your-project/
├── src/
│ └── chart.ts
├── index.html
├── tsconfig.json
├── webpack.config.js
└── package.json
Open the index.html file in a browser to see the chart.
The chart is responsive and will automatically resize based on the container size. It includes hover effects for the bars, a legend at the top, and axis labels. The background of the bars is semi-transparent, and you can easily modify the colors by changing the rgba values in the configuration. This example demonstrates how to create a bar chart using Chart.js with TypeScript. By following these steps, you'll be able to set up a TypeScript environment with Webpack to handle both TypeScript compilation and chart rendering. You can easily extend this by adding more datasets, changing the chart type, or customizing the chart further based on your needs.