Skip to content

Allow plugin resolve callbacks to mark a module as side-effect free #1009

@yifeiw3

Description

@yifeiw3

I'm using esbuild to eliminate unneeded code by bundling a virtual entry that only re-exports the needed part and mark every imports as external.

An example that transforms originalCode to only keep client side code:

const { build } = require("esbuild");

const originalCode = `
  import { serverFn } from "./server-side";
  import { clientFn } from "./client-side";

  export function server() {
    serverFn();
  }
  export function client() {
    clientFn();
  }
`;

async function main() {
  const result = await build({
    stdin: {
      contents: `export { client } from 'ORIGINAL'`,
      loader: "ts",
    },
    bundle: true,
    format: "esm",
    write: false,
    plugins: [
      {
        name: "only-export-client",
        setup: (build) => {
          build.onResolve({ filter: /.*/ }, (args) => {
            if (args.path === "ORIGINAL") {
              return {
                path: "ORIGINAL",
                namespace: "proxy",
              };
            }
            return {
              external: true,
            };
          });
          build.onLoad({ filter: /.*/, namespace: "proxy" }, async (args) => {
            return {
              contents: originalCode,
              loader: "ts",
            };
          });
        },
      },
    ],
  });

  console.log(result.outputFiles[0].text);
}
main();

The output is:

// proxy:ORIGINAL
import {serverFn} from "./server-side";
import {clientFn} from "./client-side";
function client() {
  clientFn();
}
export {
  client
};

./server-side is still imported and I guess the reason is that esbuild doesn't know whether the module is side-effect free or not.

So if it's about side-effect, is it possible to allow plugin resolve callbacks to mark a module as side-effect free? Or is there any other solution to solve this problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions