esbuild icon indicating copy to clipboard operation
esbuild copied to clipboard

plugins::onLoad dataurl should support mimetype and base64 encoder

Open mizulu opened this issue 5 months ago • 3 comments

TLDR

  1. need ability to specify mimetype when using loader:dataurl in result of the plugin onLoad
  2. need ability to specify if dataurl will be encoded with base64
build.onLoad({ filter: /.*/, namespace: "dataurl" }, async args => {
        const buffer = await fs.readFile(args.path.replace(/\?dataurl$/, ""));
        return {
          contents: bufferBuffer,
          loader: "dataurl"
        }
 };

the build output will be either

data:application/octet-stream,...

or this if the buffer does not have "binary" data

data:text/plain;charset=utf-8,...

now if I want to explicitly indicate the mimetype maybe for a image/gif or image/jpeg I can not indicate that for the loader.

if contents also accepted Blob, or blob like object we can preserve the mime type

let contents = new Blob([dataURLBuffer], { type: "image/gif" });

also need a way to indicate whether I want to use base64 encoding

build.onLoad({ filter: /.*/, namespace: "dataurl" }, async args => {
        const buffer = await fs.readFile(args.path.replace(/\?dataurl$/, ""));
        let bufferBlob= new Blob([buffer], {type:"image/gif"})
        return {
          contents: bufferBlob,
          base64: true,            // not sure how to best communicate this 
          loader: "dataurl"
        }
 };

one downside with Blob, might be that it may copy the buffer so maybe some struct support instead.

build.onLoad({ filter: /.*/, namespace: "dataurl" }, async args => {
        const buffer = await fs.readFile(args.path.replace(/\?dataurl$/, ""));
        const struct = { buffer, mime:"image/gif", base64:true} 
        return {
          contents: struct ,
          loader: "dataurl"
        }
 };

mizulu avatar Jul 09 '25 19:07 mizulu

I think you can already do that with a plugin to generate a custom content with loader: "text". example

hyrious avatar Jul 12 '25 05:07 hyrious

The dataurl already handle 99.9% of the functionally. this is a question of why not get it to 100%

I appreciate the workaround using text allows us to reimplement dataurl, but if txt can be used for that why do we need dataurl?

mizulu avatar Jul 12 '25 06:07 mizulu

why do we need dataurl?

The dataurl loader is useful for simple cases, and also for the CLI which can't use plugins.

now if I want to explicitly indicate the mimetype maybe for a image/gif or image/jpeg I can not indicate that for the loader.

The dataurl loader already automatically uses the image/gif and image/jpeg mime types for GIF and JPEG files. So you shouldn't have to do anything special here. This is something that esbuild does using Go's http.DetectContentType API which follows the specification here: https://mimesniff.spec.whatwg.org/

evanw avatar Nov 01 '25 23:11 evanw