JsBarcode is not defined

1.6k views Asked by At

Using jsbarcode in my node.js web application I am unable to get rid of error: JsBarcode is not defined.

In my .ejs file I have the following code:

<html>
<head>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>
</head>
  <body>
        <svg id="barcode"></svg>
        <% JsBarcode("#barcode", obj[0].num); %>
  </body>
</html>

I'm confused as to why JsBarcode is undefined? I have tried making sure jsbarcode is installed via npm install jsbarcode --save and in the head of my .ejs file I've included the cdn <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>

1

There are 1 answers

3
marcobiedermann On BEST ANSWER

First, EJS is a templating engine, so packages you install via NPM would not work in this case (except you inject the content).

In your scenario you could treat it like any other HTML page. Just source the library using the script tag and include your code afterward

// template.ejs

<svg id="barcode"></svg>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>
<script>
  JsBarcode('#barcode', <%- obj[0].num %>)
</script>

Note that there is also a newer version of JSBarcode available, so I guess it's also worth updating.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>