Skip to content

自定义Plugin

创建一个Plugin

Plugin 的本质是一个函数对象,在函数对象中实现setup函数,在构建开始时会遍历使用的 Plugin 对象,并且调用 Plugin 对应的setup函数,并且传入build对象。开发者可以通过build对象选择需要在哪些流程步骤中注册对应的hook即回调函数。

例:

js
import * as esbuild from "esbuild";
import path from "node:path";

let exampleOnResolvePlugin = {
  name: "example",
  setup(build) {
    // Redirect all paths starting with "images/" to "./public/images/"
    build.onResolve({ filter: /^images\// }, (args) => {
      return { path: path.join(args.resolveDir, "public", args.path) };
    });

    // Mark all paths starting with "http://" or "https://" as external
    build.onResolve({ filter: /^https?:\/\// }, (args) => {
      return { path: args.path, external: true };
    });
  },
};

await esbuild.build({
  entryPoints: ["app.js"],
  bundle: true,
  outfile: "out.js",
  Plugins: [exampleOnResolvePlugin],
  loader: { ".png": "binary" },
});