How to get SVG.JS 3.0.+ working with svgdom and node.js

Viewed 1666

SVG.js 3.0.5 has been released and i wanted to update my nodejs app, which is generating svgs using the library from 2.7 to 3.0.5.

To run this library with node.js you need to use svgdom (https://github.com/svgdotjs/svgdom)

The problem here is that the constructor changed and i can't figure out how to use it with node.js.

//previous method to initialize svgjs 2.7
const svgWindow   = require('svgdom');
const SVGJS = require("svg.js")(svgWindow);

//with version 3.0.5 the package name changed
const svgWindow = require("svgdom");
const SVGJS = require("@svgdotjs/svg.js");

SVGJS(svgWindow); //is not a function error
2 Answers

I went through the source code and it looks like this should work

const window = require("svgdom");
const SVG = require("@svgdotjs/svg.js");

SVG.registerWindow(window, window.document);

I updated the readme so that it reflects the new use better:

npm install @svgdotjs/svg.js svgdom

// returns a window with a document and an svg root node
const window = require('../svgdom')
const document = window.document
const {SVG, registerWindow} = require('@svgdotjs/svg.js')

// register window and document
registerWindow(window , window.document)

// create canvas
const canvas = SVG(document.documentElement)

// use svg.js as normal
canvas.rect(100,100).fill('yellow').move(50,50)

// get your svg as string
console.log(canvas.svg())
// or
console.log(canvas.node.outerHTML)

Please note, that svg.js v3 does not export this big object anymore. Instead you have to require the functions you need. More information in the readme: https://github.com/svgdotjs/svgdom

Related