Skip to content

Instantly share code, notes, and snippets.

@jdanyow
Created February 15, 2023 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdanyow/4a4597b06ee323458daee79565ece07b to your computer and use it in GitHub Desktop.
Save jdanyow/4a4597b06ee323458daee79565ece07b to your computer and use it in GitHub Desktop.

package.json

{
  "name": "xxxxxxx",
  "version": "1.0.0",
  "description": "Parcel reporter to emit bundle manifest",
  "main": "index.js",
  "repository": "xxxxxxx",
  "author": "xxxxxxx",
  "homepage": "xxxxxxx",
  "license": "none",
  "private": true,
  "scripts": {
    "compile": "echo compile",
    "clean": "echo clean",
    "test": "echo test"
  },
  "engines": {
    "parcel": ">=2.8.0"
  },
  "peerDependencies": {
    "parcel": "^2.8.2"
  },
  "dependencies": {
    "@parcel/plugin": "^2.8.3",
    "@parcel/core": "^2.8.3"
  }
}

index.js

const { Reporter } = require('@parcel/plugin');

exports.default = new Reporter({
  async report({ event, options }) {
    if (event.type !== 'buildSuccess') {
      return;
    }

    const { bundleGraph } = event;

    /** @type {Record<string, string>} */
    const manifest = {};

    let distDir = '';
    for (const bundle of bundleGraph.getBundles()) {
      const { name, filePath, type, target } = bundle;
      const entryFilePath = bundle.getMainEntry()?.filePath;
      if (!entryFilePath) {
        continue;
      }
      // console.log(
      //   `${type}\n${name}\n${filePath}\n${target.distEntry}\n${
      //     target.distDir
      //   }\n${entryFilePath}\n\n${filePath.substr(target.distDir.length)}<------`
      // );

      const key = entryFilePath
        .substr(process.cwd().length)
        .replace(/^\/src\//, '');
      const value = filePath.substr(target.distDir.length);
      manifest[key] = value;
      distDir = target.distDir;
    }

    // console.log(manifest, null, 2);
    const manifestFilename = 'dist/manifest.json';
    await options.outputFS.writeFile(
      manifestFilename,
      JSON.stringify(manifest, null, 2),
      null
    );
    console.log(`Manifest generated 🗺: ${manifestFilename}`);
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment