Skip to content

esbuild 的特点就是快、非常快,但产物最低能兼容到 ES6,通常更适用于面向 Node.js 平台的源码构建。

点击查看【bilibili】

概念

Namespaces

每个模块都有一个相关联的命名空间。默认情况下,esbuild 在file命名空间中操作,它对应于文件系统中的文件。但是 esbuild 也可以处理在文件系统中没有对应位置的“虚拟”模块。

插件可以用来创建虚拟模块。虚拟模块通常使用 file以外的名称空间来区别于文件系统模块。

Filters

Hooks

onResolve

使用 onResolve 添加的回调函数将在 esbuild 构建的每个模块的每个导入路径上运行。回调函数可以自定义 esbuild 如何进行路径解析。例如,它可以拦截导入路径并将它们重定向到其他地方。它还可以将路径标记为外部路径。

javascript
const exampleOnResolvePlugin = {
  name: 'example',
  setup(build) {
    const path = require('node:path')

    // 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 }
    })
  },
}

require('esbuild')
  .build({
    entryPoints: ['app.js'],
    bundle: true,
    outfile: 'out.js',
    plugins: [exampleOnResolvePlugin],
    loader: { '.png': 'binary' },
  })
  .catch(() => process.exit(1))

Transform API

Transform API 可以在不访问文件系统的情况下处理字符串。可以在没有文件系统的环境中使用或者作为其他工具链中的一部分

ts
// import { transformSync } from "esbuild";

// const code = 'let x: number = 1'

// const result = transformSync(code, {
//   loader: "ts",
//   tsconfigRaw?: string ,
//   compilerOptions?: {
//     jsxFactory?: string,
//     jsxFragmentFactory?: string,
//     useDefineForClassFields?: boolean,
//     importsNotUsedAsValues?: 'remove' | 'preserve' | 'error',
//   },
//   sourcefile?: string;
//   loader?: Loader;
//   banner?: string;
//   footer?: string;
// });

// {
//   code: 'let x = 1;\n',
//   map: '',
//   warnings: []
// }

sourcefile This option sets the file name when using an input which has no file name. This happens when using the transform API and when using the build API with stdin. The configured file name is reflected in error messages and in source maps. If it's not configured, the file name defaults to<stdin>.

Build

build API 操作文件系统中一个或多个文件,这使得文件可以相互引用并最终被打包到一起

typescript
import { build } from 'esbuild';

(async () => {
  const result = await build({
    entryPoints: ['code.ts'],
    outfile: 'out.js',
    bundle: true,
  })
  console.log('result: ', result)
})()

bundle 将文件中所有的依赖 递归打包进来,所有依赖中的依赖也会打包进来,默认不会打包

更多配置https://esbuild.github.io/api/#simple-options