简体   繁体   中英

Using svg.js with TypeScript

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?

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风格

ES 6 style ES 6风格 or ES 6风格

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM