feross / buffer

The buffer module from node.js, for the browser.
Other
1.8k stars 231 forks source link

ESM Support #336

Open naftalimurgor opened 11 months ago

naftalimurgor commented 11 months ago

Hey, Noob question here: From the docs, we should:

var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

Question: How does one use the import/export style and is it supported?

For example:

import { Buffer } from 'buffer/'

Ty!

gustawdaniel commented 11 months ago

In my case

Rollup failed to resolve import "buffer/" 
naftalimurgor commented 10 months ago

Got the same for the import syntax. Let me know once you get around this.

guest271314 commented 9 months ago

Here you go https://gist.github.com/guest271314/08b19ba88c98a465dd09bcd8a04606f6

git clone https://github.com/feross/buffer
cd buffer
bun install base64-js ieee754
bun build ./index.js --target=browser --outfile=buffer.js

Importing with node, deno, bun, quickjs-ng, txiki.js

const url =
  "https://gist.githubusercontent.com/guest271314/08b19ba88c98a465dd09bcd8a04606f6/raw/aac580355cfe4b4a0d6e20a493fca028dfe62dbb/buffer.js";

console.log(navigator.userAgent);

if (navigator.userAgent.includes("txiki.js")) {
  try {
    const { Buffer } = await import(url);
    console.log(Buffer.from([0]));
  } catch (e) {
    console.log(e);
  }
}

if (navigator.userAgent.includes("quickjs-ng")) {
  try {
    const { Buffer } = await import("../buffer/buffer.js");
    console.log(JSON.stringify([...Buffer.from([0])]));
  } catch (e) {
    console.log(e);
  }
}

if (navigator.userAgent.includes("Deno")) {
  const ab = new Blob([
    await (await fetch(url)).arrayBuffer(),
  ], {
    type: "text/javascript",
  });
  try {
    const { Buffer } = await import(URL.createObjectURL(ab));
  } catch (e) {
    console.log(e);
  }
}

if (navigator.userAgent.includes("Node")) {
  try {
    const text = await (await fetch(url)).text();
    const dataURL = `data:text/javascript;base64,${btoa(text)}`;
    const { Buffer } = await import(dataURL);
    console.log(Buffer.from([0]));
  } catch (e) {
    console.log(e);
  }
}

Bun doesn't work as expected with dynamic network imports

if (navigator.userAgent.includes("Bun")) {
  try {
    const text = await (await fetch(url)).text();
    const dataURL = `data:text/javascript;base64,${btoa(text)}`;
    const { Buffer } = await import(dataURL);
    console.log(Buffer.from([0]));
  } catch (e) {
    console.log(e);
  }
}
chjj commented 9 months ago
import { Buffer } from 'buffer/index.js';