Silly question, can't figure how to use typescript with svgdom in node.
The following TS class is used by a route in a TS node-express application.
Can you help me please to set the correct typings?
import 'svg.js';
const _window = require('svgdom');
const SVG: *???* = require('svg.js')(_window);
export class SvgTest {
draw: *???*;
constructor() {
this.init();
}
init() {
// create svg.js instance
this.draw = SVG(_window.document.documentElement);
}
drawStub(): string {
this.draw.rect(100, 100).fill('yellow').move(50, 50);
return this.draw.svg();
}
}
No one of us is using typescript so our knowledge is really limited. I am afraid I can't help you there. Maybe you find the answer in the typescript file. Isn't there some export statement which shows which type is exported?
@Pangeli70 here is how I got it working:
"use strict";
import * as svgdom from "svgdom"
import * as SVG from "svg.js"
export const svg = SVG(window)
// other work here...
Anybody else, who reaches it. The correct way of doing it is:
// tslint:disable-next-line:no-var-requires
window = require('svgdom')
export class SomeClass {
public someMethod(): string {
let SVG = require('svgjs')
const svg = SVG(window.document.documentElement)
const canvas = svg.size(110, 20)
Had similar issues. Here's one solution with the import statements and later node versions with typescript. At least at the time of writing, the registerWindow is missing from the typings; so adding it manually helps. This way typescript picks up the types (the require-way makes types any).
declare module "@svgdotjs/svg.js" {
const registerWindow: Function
}
import { SVG, Container, registerWindow } from "@svgdotjs/svg.js"
import * as svgdom from 'svgdom'
registerWindow(svgdom, svgdom.document)
const canvas = SVG(svgdom.document.documentElement) as Container
const rect = canvas.rect(100, 100).fill('#f06')
thanks @jounii
I choose another approach so I leave here my solution for references:
I add in tsconfig.json my folder for for types:
...
"compilerOptions": {
...
"typeRoots": ["./node_modules/@types", "./types"]
},
...
I then add a module declaration like this at types/svgdom.d.ts:
declare module 'svgdom' {}
I could have add proper typing but I don't need it at this stage.
For me @jounii's solution worked but with minor changes:
declare module "@svgdotjs/svg.js" {
const registerWindow: Function
}
import { SVG, Container, registerWindow } from "@svgdotjs/svg.js"
//@ts-ignore
import * as svgdom from 'svgdom'
let window = svgdom.createSVGWindow();
registerWindow(window, window.document)
const canvas = SVG(window.document.documentElement) as Container
const rect = canvas.rect(100, 100).fill('#f06')
Most helpful comment
Had similar issues. Here's one solution with the import statements and later node versions with typescript. At least at the time of writing, the registerWindow is missing from the typings; so adding it manually helps. This way typescript picks up the types (the require-way makes types any).