2

I'm making a website app using TypeScript, and I want to use the svg.js library.

I'm coding in TypeScript, and automatically compiling into JavaScript which runs in the browser.

Is this possible? And if so, how?

Magmatic
  • 1,754
  • 3
  • 19
  • 34

2 Answers2

5

svg.js provides a .d.ts file so you can use it in typescript out of box.

I am using vscode and it needs no further configuration to provide intellisense.

CommonJS style CommonJS style

ES 6 style ES 6 style or ES 6 style

vscode integrates js and ts service tightly, so it may provide some kind of auto detection. I never used Atom but I think you can explicitly declare your reference using Triple-Slash Directives

/// <reference path="path/to/yourTypeDeclaration.d.ts" />
// your code follows

If importing this still not helps, you may lack some kind of language service plugins.

obfish
  • 673
  • 4
  • 17
  • Great, so it's possible. But how? – Magmatic Feb 13 '18 at 00:11
  • @Magmatic import svg.js and just use it? What is your question? – Fuzzyma Feb 15 '18 at 11:12
  • You mention that it comes with a ".d.ts" file, but you never import it. How does my IDE (Atom) know about this file? Your code never mentions it. – Magmatic Feb 16 '18 at 03:40
  • @Fuzzyma do you maybe know why `select()` method [doesn't work](https://stackoverflow.com/questions/49387057/using-svg-select-method-with-class-selector-of-the-svg-js-library-doesnt-work/49387204#49387204) properly with typescript? Does it look like the bug? – mpro Mar 20 '18 at 14:42
  • @magmatic - I don't know. I guess you need to reference the atom docs here – Fuzzyma Mar 20 '18 at 15:25
  • @mpro could be that this methods is missing in the d.ts file. You can add it via PR – Fuzzyma Mar 20 '18 at 15:26
  • Weird, import does not find svg. But in the svg folder in node_modules is a d.ts. I'm on a simple TypeScript (3.4) project with webpack (4.32). And svg.js 3.0. – Domske May 22 '19 at 16:05
  • solved: Use `"moduleResolution": "node",` in tsconfig.json. – Domske May 22 '19 at 16:34
1

Quite late to the party but since I have wasted most of the day struggling to use svg.js from typescript I want to share the solution:

First (of course) you need to install the svg.js via npm.

nmp install svg.js --save

Installed package contains the so called typedef file svg.js.d.ts.

You will also need to setup webpack or your favorite packager in order to prepare package for the web.

In your '.ts' file you paste:

import * as SVG from 'svg.js';

function a() {
    let draw = SVG(window.document.body).size('100%', '100%')

    draw.rect(400, 400).fill({ color: '#f00', opacity: 1 })
}


window.onload = (event) => {
    a()
};

This will render a red rectangle.

Ognyan
  • 13,452
  • 5
  • 64
  • 82