Issues with bwip-js `toCanvas` method in a React TypeScript application

413 views Asked by At

I'm working with bwip-js in my React TypeScript application and I'm encountering a problem with the toCanvas method. When I try to use it, I receive the error: Property 'toCanvas' does not exist on type 'typeof BwipJs'.

Upon inspecting the bwip-js type in VS Code, it appears to be importing the Node module type instead of the browser module type. The package.json can be found here: bwip-js package.json

In an attempt to resolve this, I tried to directly import the browser module type with the following line: import BwipJs from "bwip-js/dist/bwip-js.js";. VS Code seems to be fine with this and it recognizes the toCanvas method. However, when I run the application, I'm presented with a new error:

Module not found: Error: Package path ./dist/bwip-js.js is not exported from package \node_modules\bwip-js (see exports field in \node_modules\bwip-js\package.json)

Does anyone have any insights on how I can successfully use the toCanvas method from bwip-js in a browser environment within a React TypeScript application? Any help would be greatly appreciated.

Additional Information:

Node.js Version: v18.12.1

React Version: ^18.2.0

TypeScript Version: ^4.9.5

bwip-js Version: ^4.0.1

Installation Method: The bwip-js library was installed via npm, as indicated in the package.json file.

Relevant Dependencies: Other dependencies that might interact with bwip-js include:
    @types/node: ^16.18.38
    @types/react: ^18.2.14
    buffer: ^6.0.3

My code:

import React, { useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
import bwipjs from 'bwip-js';

const App = () => {
  useEffect(() => {
    try {
      // The return value is the canvas element
      let canvas = bwipjs.toCanvas('mycanvas', {
                bcid:        'code128',       // Barcode type
                text:        '0123456789',    // Text to encode
                scale:       3,               // 3x scaling factor
                height:      10,              // Bar height, in millimeters
                includetext: true,            // Show human-readable text
                textxalign:  'center',        // Always good to set this
            });
    } catch (e) {
        // `e` may be a string or Error object
    }
  }, []);

  return (
    <div className="App">
      <div className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h2>Welcome to React</h2>
      </div>
      <canvas id="mycanvas"></canvas>
    </div>
  );
}

export default App;
0

There are 0 answers