Generating QR code with Javascript

We can generate QR codes using the package qrcode. If we just want this as tooling, such as manually generating, then we can add the following

npm install qrcode --save-dev

Now update your packages.json with this script

"generate:qrs": "node ./scripts/generate-qrs.mjs",

As yo can see, add a scripts folder and create the file generates-qrs.mjs with the following code

import QRCode from 'qrcode';
import fs from 'fs/promises';
import path from 'path';

const outDir = path.join(process.cwd(), 'public', 'qrcodes');
await fs.mkdir(outDir, { recursive: true });

const sites = [
  { name: 'www.mywebsite.co.uk', url: 'https://www.mywebsite.co.uk' },
];

for (const site of sites) {
  const pngPath = path.join(outDir, `${site.name}.png`);
  const svgPath = path.join(outDir, `${site.name}.svg`);

  console.log(`Generating ${pngPath} and ${svgPath}`);

  // PNG (300x300)
  await QRCode.toFile(pngPath, site.url, { width: 300 });

  // SVG
  const svgString = await QRCode.toString(site.url, { type: 'svg' });
  await fs.writeFile(svgPath, svgString, 'utf8');
}

console.log(`QR codes generated in ${outDir}`);

In the above, the sites include a name, this is the name of the file ad we’ll create a file of type and with suffix PNG and SVG. The url is what’s embedded into the QR code.