LoginSignup
1
0

More than 1 year has passed since last update.

Node.jsでd3.jsを使うミニマムな手順

Last updated at Posted at 2023-02-11

d3.jsは、グラフのようなデータ可視化を行うためよく利用されているライブラリである。
通常Webフロントエンドに組み込まれて使われるが、画像生成をバックエンドでも使えるようにしてみたい。

ここでは、Node.jsでd3.jsを使うミニマムな手順をまとめる。
d3.jsの現行バージョンはESMのみ対応になっているため、ESMに対応した手順にする。
まずJavaScriptの場合の手順をまとめ、それに続いてTypeScriptを使う場合の手順も記載する。

環境

  • Node.js 18.13.0
  • Ubuntu 20.04 LTS (WSL2)
  • Visual Studio Code 1.73.0

JavaScriptの場合の手順

touch package.json

package.jsonに以下を記入

{
  "dependencies": {
    "d3": "^7.8.2",
    "jsdom": "^21.0.0"
  },
  "type": "module"
}
npm install
touch sample.js

sample.jsに以下を記入

import * as d3 from 'd3'
import { JSDOM } from 'jsdom'
const document = new JSDOM().window.document
const svg = d3.select(document.body).append('svg')
svg.attr('width', 400)
svg.attr('height', 400)
svg.append('circle')
 .attr('cx', 200)
 .attr('cy', 200)
 .attr('r', 40)
 .attr('fill', "blue")

console.log(document.body.innerHTML)
node sample.js > out.svg

out.svgとして、背景は透明な、以下のような青丸の画像が出力される。

image.png

TypeScriptの場合の手順

上記手順で作った環境とは別に、一からプロジェクトを作成していきます。

npm init
npm i d3 jsdom @types/d3 @types/jsdom typescript @types/node@18 # 使ってるnodejsのバージョンに合わす
npx tsc --init

package.jsonに以下を追記

"type": "module"

tsconfig.jsonを以下に書き換え("module" : "ES2015"がポイント)

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "./dist",
    "target": "es2016", 
    "module": "ES2015",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,   
    "skipLibCheck": true
  },
  "include": [
    "src/**/*"
  ],
}
mkdir src
touch src/index.ts

src/index.tsに以下を書く

import * as d3 from 'd3'
import { JSDOM } from 'jsdom'

function run(): string {
    const document = new JSDOM().window.document
    const svg = d3.select(document.body).append('svg')
    svg.attr('width', 400)
    svg.attr('height', 400)
    svg.append('circle')
    .attr('cx', 200)
    .attr('cy', 200)
    .attr('r', 40)
    .attr('fill', "blue")
    return document.body.innerHTML
}
  
console.log(run());
npx tsc
# 動作確認
node dist/index.js > out.svg

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0