Import Canvg v4 in TypeScript project

68 views Asked by At

I have an old TypeScript project with the following tsconfig:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es5",
    "lib": ["es7", "dom"],
    ...

When I import it regularly (i.e. import { Canvg } from 'canvg';) the compiler complains about the ES6 syntax in the library:

Failed to compile.

./node_modules/canvg/dist/index.js
Module parse failed: Unexpected token (3822:16)
You may need an appropriate loader to handle this file type.
|             const dyY = Math.cos(-rotation) * dy;
|             segment.p0 = {
|                 ...p0,
|                 x: p0.x + dyX,
|                 y: p0.y + dyY

I tried to import the library independently as static file but I could only find v3 and didn't work for the files I needed while the latest v4 demo works perfectly.

Any idea how I can get unstuck? Thanks!

1

There are 1 answers

0
Nuthinking On

I ended up generating the v4 single bundle file using this Webpack configuration:

const path = require('path');

module.exports = {
  entry: './index.js', // Adjust this path to your module's entry point
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'canvg.js',
    library: 'Canvg', // This is the name you'll use to access the module from the window object
    libraryTarget: 'window',
  },
};

And exposing the function I needed:

import { Canvg } from 'canvg';

export const fromString = Canvg.fromString;

Also, the reason why the v3 wasn't working for me is that I wasn't waiting for the rendering before extracting the image from the canvas ✌️

await v.render();