qrcodedemo/STANDALONE_BUNDLE.md
Michael Mainguy 874f3c4412 Add standalone bundle for qrCodeUtils with all dependencies
- Created vite.standalone.config.js for optimized bundle building
- Added build scripts for standalone bundle generation
- Generated three formats: IIFE (28KB), UMD (28KB), ES Module (61KB)
- Includes all dependencies: qrcode and imagetracer
- Added comprehensive documentation and examples
- Created build script with detailed bundle information
- Added terser for minification optimization
- Fixed package.json dependencies and scripts
2025-08-01 17:17:36 -05:00

7.7 KiB

Standalone QR Code Utils Bundle

A complete, self-contained bundle of the QR Code Generator utilities that includes all dependencies. No external dependencies required!

📦 Bundle Files

The standalone build creates three formats in the dist/ directory:

  • qr-code-utils.iife.js (28 KB) - Immediately Invoked Function Expression (IIFE) for browser use
  • qr-code-utils.umd.js (28 KB) - Universal Module Definition for Node.js and bundlers
  • qr-code-utils.es.js (61 KB) - ES Module for modern bundlers and browsers

🚀 Quick Start

Browser (IIFE)

<!DOCTYPE html>
<html>
<head>
    <title>QR Code Generator</title>
</head>
<body>
    <div id="app"></div>
    
    <!-- Load the standalone bundle -->
    <script src="qr-code-utils.iife.js"></script>
    <script>
        // All functions are available on window.QRCodeUtils
        async function generateQR() {
            const qrCode = await window.QRCodeUtils.generateQRCode('Hello World');
            console.log(qrCode); // data:image/png;base64,...
        }
        
        generateQR();
    </script>
</body>
</html>

ES Module

import { generateQRCode, generateCompleteSVGQRCode } from './qr-code-utils.es.js';

// Generate basic QR code
const qrCode = await generateQRCode('Hello World');

// Generate QR code with custom image
const svgContent = await generateCompleteSVGQRCode(
    'Hello World',
    'data:image/png;base64,...', // Custom image
    20, // Image size percentage
    '#000000', // Foreground color
    '#FFFFFF'  // Background color
);

Node.js (UMD)

const { generateQRCode } = require('./qr-code-utils.umd.js');

async function generateQR() {
    const qrCode = await generateQRCode('Hello World');
    console.log(qrCode);
}

generateQR();

🔧 Building the Bundle

Prerequisites

npm install

Build Commands

# Build standalone bundle
npm run build:standalone

# Build with detailed info
npm run build:standalone:info

Build Configuration

The standalone bundle is configured in vite.standalone.config.js:

  • Entry Point: src/utils/qrCodeUtils.js
  • Dependencies Included: qrcode, imagetracer
  • Formats: ES Module, UMD, IIFE
  • Optimization: Minified with Terser
  • Target: ES2018 for modern browser support

📋 Included Functions

Core QR Code Generation

  • generateQRCode(text, foregroundColor, backgroundColor) - Generate PNG QR code
  • generateSVGQRCode(text, foregroundColor, backgroundColor) - Generate SVG QR code
  • generateCompleteSVGQRCode(text, imageUrl, imageSize, foregroundColor, backgroundColor) - Complete QR code with image

Image Processing

  • addImageToQRCode(qrCodeUrl, imageUrl, imageSize) - Add image to PNG QR code
  • addImageToSVG(svgString, imageUrl, imageSize) - Add image to SVG QR code
  • vectorizeBitmap(img, targetSize, x, y, svgDoc) - Convert bitmap to vector

Utilities

  • downloadSVG(svgContent, filename) - Download SVG file
  • fileToDataURL(file) - Convert file to data URL
  • validateImageFile(file, maxSize) - Validate image file

🎯 Use Cases

1. Static Websites

<script src="qr-code-utils.iife.js"></script>
<script>
    // Generate QR codes without any build process
    window.QRCodeUtils.generateQRCode('https://example.com')
        .then(qrCode => {
            document.getElementById('qr-code').src = qrCode;
        });
</script>

2. CDN Distribution

<!-- Load from CDN -->
<script src="https://cdn.example.com/qr-code-utils.iife.js"></script>

3. Node.js Applications

const { generateCompleteSVGQRCode } = require('./qr-code-utils.umd.js');

// Generate QR codes on the server
const svgContent = await generateCompleteSVGQRCode(
    'https://example.com',
    logoDataUrl,
    25,
    '#1a1a1a',
    '#ffffff'
);

4. Modern Bundlers (Webpack, Rollup, Vite)

import { generateQRCode } from './qr-code-utils.es.js';

// Tree-shakeable imports
const qrCode = await generateQRCode('Hello World');

📊 Bundle Analysis

Size Breakdown

  • IIFE/UMD: ~28 KB (gzipped: ~10.5 KB)
  • ES Module: ~61 KB (gzipped: ~15 KB)
  • Source Maps: ~140 KB each

Dependencies Included

  • qrcode: QR code generation library
  • imagetracer: Bitmap to vector conversion
  • All utilities: Complete set of helper functions

Browser Support

  • ES2018+: Modern browsers with ES6+ support
  • Canvas API: Required for image processing
  • File API: Required for file uploads
  • Blob API: Required for downloads

🔍 Bundle Contents

The standalone bundle includes:

  1. QR Code Generation: Complete QR code generation with error correction
  2. Image Processing: Custom image embedding with white background
  3. Vectorization: Bitmap to SVG vector conversion
  4. File Handling: File validation and data URL conversion
  5. Download Utilities: SVG download functionality
  6. Error Handling: Comprehensive error handling and validation

🛠️ Customization

Modify Bundle Configuration

Edit vite.standalone.config.js:

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, 'src/utils/qrCodeUtils.js'),
      name: 'QRCodeUtils', // Change global variable name
      formats: ['es', 'umd', 'iife'], // Choose formats
      fileName: (format) => `my-qr-utils.${format}.js` // Custom filename
    },
    rollupOptions: {
      external: [], // Add external dependencies if needed
      output: {
        globals: {} // Define global variables for externals
      }
    }
  }
});

Exclude Dependencies

To exclude dependencies and use them as externals:

rollupOptions: {
  external: ['qrcode', 'imagetracer'],
  output: {
    globals: {
      qrcode: 'QRCode',
      imagetracer: 'ImageTracer'
    }
  }
}

🧪 Testing the Bundle

Browser Test

  1. Build the bundle: npm run build:standalone
  2. Open examples/standalone-bundle-example.html in a browser
  3. Test all features: QR generation, image upload, SVG export

Node.js Test

const { generateQRCode } = require('./dist/qr-code-utils.umd.js');

generateQRCode('Test QR Code')
  .then(qrCode => console.log('QR Code generated:', qrCode.substring(0, 50) + '...'))
  .catch(error => console.error('Error:', error));

📈 Performance

Bundle Optimization

  • Tree Shaking: ES module format supports tree shaking
  • Minification: Terser optimization for smallest bundle size
  • Source Maps: Development debugging support
  • Gzip Compression: Optimized for network transfer

Runtime Performance

  • Async Operations: All functions return promises for non-blocking execution
  • Memory Efficient: Proper cleanup of canvas and blob objects
  • Error Recovery: Graceful fallbacks for failed operations

🔒 Security

File Validation

  • Type Checking: Validates image file types
  • Size Limits: Configurable file size limits
  • Data URL Safety: Secure data URL generation

XSS Prevention

  • Input Sanitization: Validates all input parameters
  • Safe DOM Manipulation: Uses safe DOM methods
  • Error Handling: Prevents information leakage

📚 Examples

See the following examples for complete usage:

  • examples/standalone-bundle-example.html - Complete browser example
  • examples/vanilla-js-example.html - Vanilla JavaScript with modules
  • src/components/TextAreaComponent.jsx - React component usage

🤝 Contributing

To modify the standalone bundle:

  1. Update src/utils/qrCodeUtils.js with new functions
  2. Test with npm run build:standalone
  3. Verify functionality in examples/standalone-bundle-example.html
  4. Update documentation as needed

📄 License

MIT License - Same as the main project