Git Product home page Git Product logo

Comments (3)

guesant avatar guesant commented on May 31, 2024 1

POC to generate a single browser-polyfill.js in the production build

.parcelrc:

{
  "extends": "@parcel/config-webextension",
  "transformers": {
    "*browser-polyfill*": [
      "@parcel/transformer-raw"
    ]
  },
  "optimizers": {
    "*browser-polyfill*": []
  },
  "packagers": {
    "*browser-polyfill*": "@parcel/packager-raw"
  }
}

no optimizations

source/manifest.json (just with the changes):

{
  "content_scripts": [
    {
      "js": ["npm:webextension-polyfill", "content.js"]
    }
  ],
  "background": {
    "scripts": ["npm:webextension-polyfill", "background.js"]
  }
}

source/*.html (just with the changes):

<script src="npm:webextension-polyfill"></script>

Now we have a new problem: the parcel is generating two bundles:

image

  • one for the HTML files: /browser-polyfill.272334ed.js

  • one for the "background" and "content-script": /up_/node_modules/webextension-polyfill/dist/browser-polyfill.js


Unify the generated browser-polyfill bundles

With node

scripts/unify-browser-polyfill.js:

#!/usr/bin/env node

const {
  readFileSync,
  unlinkSync,
  writeFileSync,
  copyFileSync,
  readdirSync,
  rmdirSync,
} = require("fs");
const { resolve, dirname } = require("path");

const recursivelyDeleteDirectoryIfEmpty = async (baseDir) => {
  if (readdirSync(baseDir).length === 0) {
    rmdirSync(baseDir);

    const parentDir = dirname(baseDir);

    if (parentDir !== "/" && parentDir !== "." && parentDir !== "") {
      return recursivelyDeleteDirectoryIfEmpty(parentDir);
    }
  }
};

import("globby").then(({ globby }) => {
  const unifyBrowserPolyfill = async () => {
    const DIST_DIR = process.env.DIST_DIR ?? resolve(__dirname, "../dist");

    const {
      DIST_BUNDLE_PATH = "browser-polyfill.js",
      WEBEXTENSION_POLYFILL_PACKAGE = "webextension-polyfill",
    } = process.env;

    process.chdir(DIST_DIR);

    const browserPolyfillBundles = await globby("**/browser-polyfill*.js");

    const allOtherProjectFiles = await globby([
      "**/*",
      ...browserPolyfillBundles.map((i) => `!${i}`),
    ]);
    
    await Promise.all(
      allOtherProjectFiles.map(async (projectFile) => {
        const fileContent = readFileSync(projectFile, "utf-8");

        const updatedFileContent = browserPolyfillBundles.reduce(
          (acc, browserPolyfillBundle) =>
            acc.replaceAll(browserPolyfillBundle, DIST_BUNDLE_PATH),
          fileContent
        );

        writeFileSync(projectFile, updatedFileContent);
      })
    );

    await Promise.all(
      browserPolyfillBundles.map(async (browserPolyfillBundle) => {
        unlinkSync(browserPolyfillBundle);
        await recursivelyDeleteDirectoryIfEmpty(dirname(browserPolyfillBundle));
      })
    );

    const resolvedWebExtensionPolyfillPackagePath = require.resolve(
      WEBEXTENSION_POLYFILL_PACKAGE
    );

    copyFileSync(resolvedWebExtensionPolyfillPackagePath, DIST_BUNDLE_PATH);
  };

  unifyBrowserPolyfill();
});

With bash + linux

scripts/unify-browser-polyfill.sh:

#!/usr/bin/env bash

set -x

cd ./distribution;

find * -name browser-polyfill\* | xargs -I '{bundle}' find . -type f -exec sed -i 's|/{bundle}|/browser-polyfill.js|' {} \+;

find * -prune -name browser-polyfill\*;

find . -type d -empty -print -delete

cp $(node -p "require.resolve('webextension-polyfill')") ./browser-polyfill.js

from browser-extension-template.

fregante avatar fregante commented on May 31, 2024

I didn't notice your comment until now, thanks for the extensive details, but I'd strongly advise against making such changes outside Parcel as it could break in any update and it's not really worth it just to save one duplicate.

Now we have a new problem: the parcel is generating two bundles:

I'd rather open an issue on Parcel’s repo to resolve that instead.

from browser-extension-template.

fregante avatar fregante commented on May 31, 2024

πŸ‘† The polyfill is no longer necessary when using manifest v3 so it has been dropped

from browser-extension-template.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.