ESbuild 在捆绑 GSAP 时失败

问题描述 投票:0回答:0

我有一个项目,我正在使用 esbuild 捆绑一些使用 GSAP 的模块。当我初始化一个基本时间线然后构建项目时,构建文件返回了一个错误,表明“GSAP 尚未初始化”。捆绑文件输出显示在屏幕截图中。Bundle file

预捆绑文件如下所示:

import { gsap } from 'gsap';

window.Webflow ||= [];
window.Webflow.push(() => {
  const name = 'Hello World';
  const tl = gsap.timeline();
});

在这里构建文件:

/* eslint-disable no-console */
import * as esbuild from 'esbuild';
import { readdirSync } from 'fs';
import { join, sep } from 'path';

// Config output
const BUILD_DIRECTORY = 'dist';
const PRODUCTION = process.env.NODE_ENV === 'production';

// Config entrypoint files
const ENTRY_POINTS = ['src/index.ts'];

// Config dev serving
const LIVE_RELOAD = !PRODUCTION;
const SERVE_PORT = 3000;

// Create context
const context = await esbuild.context({
  bundle: true,
  entryPoints: ENTRY_POINTS,
  outdir: BUILD_DIRECTORY,
  minify: PRODUCTION,
  sourcemap: !PRODUCTION,
  target: PRODUCTION ? 'es2019' : 'esnext',
  inject: LIVE_RELOAD ? ['./bin/live-reload.js'] : undefined,
  define: {
    SERVE_PORT: `${SERVE_PORT}`,
  },
});

// Build files in prod
if (PRODUCTION) {
  await context.rebuild();
  context.dispose();
}

// Watch and serve files in dev
else {
  await context.watch();
  await context
    .serve({
      servedir: BUILD_DIRECTORY,
      port: SERVE_PORT,
    })
    .then(({ port }) => {
      logServedFiles(BUILD_DIRECTORY, port);
    });
}

/**
 * Logs information about the files that are being served during local development.
 * @param {string} servedir
 * @param {number} port
 */
function logServedFiles(servedir, port) {
  /**
   * Recursively gets all files in a directory.
   * @param {string} dirPath
   * @returns {string[]} An array of file paths.
   */
  const getFiles = (dirPath) => {
    const files = readdirSync(dirPath, { withFileTypes: true }).map((dirent) => {
      const path = join(dirPath, dirent.name);
      return dirent.isDirectory() ? getFiles(path) : path;
    });

    return files.flat();
  };

  const files = getFiles(servedir);

  const filesInfo = files
    .map((file) => {
      if (file.endsWith('.map')) return;

      // Normalize path and create file location
      const paths = file.split(sep);
      paths[0] = `http://localhost:${port}`;

      const location = paths.join('/');

      // Create import suggestion
      const tag = location.endsWith('.css')
        ? `<link href="${location}" rel="stylesheet" type="text/css"/>`
        : `<script defer src="${location}"></script>`;

      return {
        'File Location': location,
        'Import Suggestion': tag,
      };
    })
    .filter(Boolean);

  console.table(filesInfo);
}

当时间线的定义被注释掉并重新构建时,错误不再出现。

预期行为:构建时,生成的文件不包含 RefrenceError。

这里有人有什么见解吗?

javascript gsap pnpm esbuild
© www.soinside.com 2019 - 2024. All rights reserved.