0

I want to create an ES module which can be easily imported in a frontend environment (in my test case angular). However I have a commonjs module in my dependencies which uses some node functionalities. At the current state my module is only usable if there are some polyfills defined within angular (I found them here: global, buffer, process ):

// in polyfills.ts
(window as any).global = window;
global.Buffer = global.Buffer || require("buffer").Buffer;
import * as process from "process";
window["process"] = process;

My goal is to build my module in a way that nothing needs to be done on the frontend side except installing the package. For this I want to move the polyfill part down a level to my module.

To reach this goal I am trying to bundle my module using webpack and defining the polyfills there. This is my current config:

import path from "path";
import { fileURLToPath } from "url";
import { createRequire } from "module";
import webpack from "webpack";

const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  entry: "./src/index.ts",
  module: {
    rules: [
      {
        test: /\.ts?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
  ],
  resolve: {
    fallback: {
      buffer: require.resolve("buffer"),
      process: require.resolve("process"),
    },
    extensionAlias: {
      ".js": [".ts", ".js"],
      ".mjs": [".mts", ".mjs"],
    },
  },
  experiments: {
    outputModule: true,
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    library: {
      type: "module",
    },
  },
};

Webpack runs this config without errors (only with size related warnings) but when I include the bundle into angular and remove the buffer polyfill there I still get the runtime error Buffer is not defined (chrome).

Is this a minor error in my config or did I miss something important which makes my whole approach unreasonable?

dude
  • 79
  • 6

0 Answers0