yarnpkgsveltekitbwip-js

Sveltekit bwip-js QRCode


Its probably a newbie problem (Not understanding what is difference between, nodejs, browser and react code). I am using bwipjs-js to generate QR code in my sveltekit app. I am using bwipjs (toCanvas(...) method) in my myqr.ts file.

It works fine and generates the QR codes. But running

yarn unit.test generates the below error.

Property 'toCanvas' does not exist on type 'typeof BwipJs'.

    1190     bwipjs.toCanvas(tempCanvas, qrOptions);

yarn unit-test must pass in order for the code to go into production.

I have tried importing the bwip-js in different ways as under:

// import bwipjs from 'bwip-js';
import * as bwipjs from 'bwip-js';
// import { gs1_128 } from 'bwip-js';

code used to generate the QR:

    let tempCanvas = document.createElement('canvas') as HTMLCanvasElement;
    try {
        bwipjs.toCanvas(tempCanvas, qrOptions);
        // const generateQR = async () => (await gs1_128(qrOptions));
        // qrImage.setAttribute('xlink:href', generateQR());    
    } catch (e) {
        console.error('Error creating QR.', extract400Error(e));
    }

If I use the third option import { gs1_128 } from 'bwip-js'; then the error is not thrown while running the test but an error is raised while running the code (in other words it doesnot run / generate QR codes).

I can see in the bwip-js documentation for react usage there is this toCanvas method used.

I am not sure how to fix the issue. Which version should I use here (node, browser, react, Browser ES6)? I actually have no clue what is going on here.

I can see that toCanvas(...) method is present in the file 'node_modules/bwip-js/dist/bwip-js.d.ts,'.

Many thanks for explanation and solution.


Solution

  • It seems, that

        import * as bwipjs from 'bwip-js';
    

    looks into bwip-js's package.json and imports different files for the typescript compiler and the generated javascript code, respectively: the compiler compiles against bwip-js-node.d.ts, which for some reason does not contain the toCanvas function, while the compiled code contains bwip-js.d.ts, which has this function.

    As long as the bwip-js author does not fix it, the following workaround worked for me:

        import * as bwipjs from 'bwip-js';
        ...
        (bwipjs as any).toCanvas(...);