
本文介绍如何使用 Esbuild 插件和 `define` 功能,针对既有 IIFE 模块又有 ESM 模块的项目,实现同时生成多个独立的 IIFE 文件和一个 ESM 打包文件的混合打包方案。通过自定义 Esbuild 插件移除 IIFE 构建中的 import 语句,并利用 `define` 功能在不同构建目标中切换代码逻辑,最终实现更简洁、更高效的打包流程。
在一些老项目中,可能同时存在使用 IIFE (Immediately Invoked Function Expression) 编写的模块和使用 ESM (ECMAScript Modules) 编写的模块。IIFE 模块通常依赖全局变量,而 ESM 模块则使用 import 和 export 进行模块化。如何使用 Esbuild 同时构建这两种类型的模块,是一个值得探讨的问题。
核心思路是利用 Esbuild 的插件机制和 define 功能,针对不同的构建目标(IIFE 和 ESM)进行定制化处理。
移除 IIFE 构建中的 import 语句: 通过自定义 Esbuild 插件,拦截 import 语句,并将其替换为空字符串。由于 IIFE 模块依赖全局变量,因此不需要 import 语句。
立即进入“豆包AI人工智官网入口”;
立即学习“豆包AI人工智能在线问答入口”;
使用 define 功能切换代码逻辑: 在代码中使用 define 定义的变量,例如 IIFE_ONLY,根据构建目标的不同,赋予不同的值。在 IIFE 构建中,IIFE_ONLY 为 true,在 ESM 构建中,IIFE_ONLY 为 false。这样,就可以根据不同的构建目标,执行不同的代码逻辑。
以下代码展示了如何创建一个 Esbuild 插件,用于移除 IIFE 构建中的 import 语句:
const removeImportsPlugin = {
  name: 'remove-imports-plugin',
  setup(build) {
    build.onResolve({ filter: /.*/ }, (args) => {
      if (args.kind !== 'entry-point') {
        return { path: args.path + '.js', namespace: 'import-ns' }
      }
    });
    build.onLoad({ filter: /.*/, namespace: 'import-ns' }, () => ({
      contents: `// empty string, do nothing`,
      loader: 'js',
    }));
  }
};这个插件包含两个部分:
在代码中使用 define 定义的变量,例如 IIFE_ONLY,根据构建目标的不同,赋予不同的值。例如:
// imports will be auto-dropped in iife by custom plugin
import { SlickEvent as SlickEvent_, Utils as Utils_ } from '../slick.core';
// for (iife) load `Slick` methods from global window object, or use imports for (cjs/esm)
const SlickEvent = IIFE_ONLY ? Slick.Event : SlickEvent_;
const Utils = IIFE_ONLY ? Slick.Utils : Utils_;
// ...
// then use it normally in the code...
const options = Utils.extend(true, {}, defaults, options);以下代码展示了如何使用 Esbuild 构建 IIFE 和 ESM 模块:
import { build } from 'esbuild';
/** build as iife, every file will be bundled separately */
export async function buildIifeFile(file) {
  build({
    entryPoints: [file],
    format: 'iife',
    // add Slick to global only when filename `slick.core.js` is detected
    globalName: /slick.core.js/.test(file) ? 'Slick' : undefined,
    define: { IIFE_ONLY: 'true' },
    outfile: `dist/browser/${file.replace(/.[j|t]s/, '')}.js`,
    plugins: [removeImportsPlugin],
  });
}
// bundle in ESM format into single file index.js
export function buildEsm() {
  build({
    entryPoints: ['index.js'],
    format: 'esm',
    target: 'es2020',
    treeShaking: true,
    define: { IIFE_ONLY: 'false' },
    outdir: `dist/esm`,
  });
}在构建 IIFE 模块时,需要指定 format: 'iife',并设置 define: { IIFE_ONLY: 'true' },同时使用 removeImportsPlugin 移除 import 语句。 globalName 选项可以设置全局变量名,只有核心文件需要设置。
在构建 ESM 模块时,需要指定 format: 'esm',并设置 define: { IIFE_ONLY: 'false' }。
假设有以下代码:
// plugins/slick.cellcopymanager.js
import { SlickEvent as SlickEvent_, Utils as Utils_ } from '../slick.core';
// for (iife) load `Slick` methods from global window object, or use imports for (cjs/esm)
const SlickEvent = IIFE_ONLY ? Slick.Event : SlickEvent_;
const Utils = IIFE_ONLY ? Slick.Utils : Utils_;
function CellCopyManager() {
  // ...
}构建后的 IIFE 模块代码如下:
"use strict";
(() => {
  // plugins/slick.cellcopymanager.js
  var SlickEvent = Slick.Event, Utils = Slick.Utils;
  function CellCopyManager() {
// ...构建后的 ESM 模块代码如下:
// plugins/slick.cellcopymanager.js
var SlickEvent5 = SlickEvent, Utils10 = Utils;
function CellCopyManager() {
// ...通过使用 Esbuild 插件和 define 功能,可以轻松地实现 IIFE 和 ESM 混合打包。这种方案不仅能够生成符合不同规范的模块,还能够避免冗余代码,提高构建效率。
以上就是使用 Esbuild 插件和 Define 实现 IIFE 和 ESM 混合打包的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号