'Issues with build of a project using pdf.js

I'm having issues creating a client side build of my project to run in browser and be hosted on Github pages. Currently when running on Nodejs (using yarn dev / vite) it works perfectly and has no errors or warnings.

The project is a Vue3 website using vite. Part of the sites functionality is to merge PDF files on the clients browser so they do not need to be uploaded to a server.

To achieve this I'm using pdf-merger-js which has a dependency on pdfjs.

When I go to the website after putting it onto my Github pages I get this error in the console:

uncaught TypeError: Class extends value undefined is not a constructor or null
    at index.84181eae.js:20753:20

I've isolated the issue to a single line of code in the pdfjs library.

The line of code in the compiled Javascript bundle is:

const Text = text.exports = class Text2 extends Fragment$5 {

There are three other instances where it successfully extends a class with Fragment. It doesn't report those errors, however those lines are below the line it does report - so it could be it'd only pick those up when it reaches them.

The error is only present when I import the PDFMerger object from pdf-merger-js, without it the rest of the site works fine and does not crash when loading after visiting it on Github pages.

I currently have two theories on why it does not work is that either pdf-merger-js or pdfjs is not supported natively on the browser or that something those two libraries do is not handled correctly by vite when it is building the project.

I'm quite new to Vue3 so I'm unsure what the issue is ultimately or if I'm doing something wrong.

Below is my vite.config.js

import { fileURLToPath, URL } from "url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), vueJsx()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  define: {
    global: "window", // required as some issues with pdf-merger-js
  },
  base: "/web-utilities/",
  build: {
    minify: false,
    target: "es2020"
  }
});

I had to define global to get the pdf merger working in the first place, otherwise I'd have issues with it saying global is undefined -- additional global related setup can be seen in my apps entry point main.js.

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { Buffer } from "buffer";
import process from "process";

window.Buffer = Buffer;
window.process = process;

const app = createApp(App);

app.use(router);

app.mount("#app");

Buffer and process were two additional global properties I required to get the pdf merger to work.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source