evanw / esbuild

An extremely fast bundler for the web
https://esbuild.github.io/
MIT License
38.16k stars 1.15k forks source link

add more meta info in result chunk #1381

Open hardfist opened 3 years ago

hardfist commented 3 years ago

Currently esbuild result.outputFiles only has text,path and content info in chunk, but we may need more meta info some times, for example

const result = esbuild.build({
    entryPoints: {
        'out/pageA': 'src/pageA',
        'out/pageB' : 'src/pages/pageB'
    }
})
result.outputFiles.forEach((chunk, idx) => {
    if(chunk.isEntry()){
         let content = injectRuntime(chunk.text);
         fs.writeFileSync(chunk.name, content); // custom outdir path depends on input key
     }else {
        let content = chunk.text
        fs.writeFileSync(chunk.name,content);
    }
})

rollup's generateBundle has rich meta in chunk ,which is convenient

evanw commented 3 years ago

Metadata for both input files and output files is accessible with the metafile feature: https://esbuild.github.io/api/#metafile

hardfist commented 3 years ago

Metadata for both input files and output files is accessible with the metafile feature: https://esbuild.github.io/api/#metafile

its not easy to get chunk info from metafile when deals with multi entry

evanw commented 1 year ago

The entryPoint property was added to the metafile in version 0.8.51. I believe using that should be sufficient to address this:

 const result = esbuild.build({
     entryPoints: {
         'out/pageA': 'src/pageA',
         'out/pageB' : 'src/pages/pageB'
     },
+    metafile: true,
 })
 result.outputFiles.forEach((chunk, idx) => {
-    if(chunk.isEntry()){
+    if(result.metafile[path.relative(__dirname, chunk.path)].entryPoint){
          let content = injectRuntime(chunk.text);
          fs.writeFileSync(chunk.name, content); // custom outdir path depends on input key
      }else {
         let content = chunk.text
         fs.writeFileSync(chunk.name,content);
     }
 })
TomokiMiyauci commented 8 months ago

Is there a way to distinguish between entry points and dynamically imported entry points from a metafile?

I would like to do the following:

declare const extractBootstraps: (result: BuildResult) => string[];
declare const entryPoints: string[];
declare const outdir: string;

const result = await build({
  entryPoints,
  outdir,
  format: "esm",
  bundle: true,
  splitting: true,
  write: false,
  metafile: true,
});
const bootstraps = extractBootstraps(result);

const hmtl = `<html>
  <body>
  ${bootstraps.map((path) => 
    `<script type="module" src="${path}"></script>`
  )}
  </body>
</html>`

"bootstrap" is all entry points in the build result, excluding entry points that are dynamically imported.

The entryPoint field allows you to distinguish between entry points and chunks. However, files that are dynamically imported also have an entryPoint field.