Skip to content

[Unity] esbuild ESM转译的问题 #2008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
hypercross opened this issue Mar 26, 2025 · 0 comments
Open

[Unity] esbuild ESM转译的问题 #2008

hypercross opened this issue Mar 26, 2025 · 0 comments

Comments

@hypercross
Copy link

当前生成的类型定义依赖namespace,对于ts的代码补全来说不甚友好。在编辑器里打Debu之后,期望编辑器补全Debug并自动添加import,但是如果只有一个namespace CS的话就做不到。

可以通过declare module "unityengine" { export = CS.UnityEngine; }这样的方法来实现上述效果,但这样的话就会需要puerts能够识别unityengine这个module,或者通过打包把unityengine转译为CS.UnityEngine

通过esbuildesbuild-plugin-external-global插件,可以几乎做到这一点,但是有个问题就是esbuild__toESM会转换一遍CS.UnityEngine再导出:

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// external-global-plugin:unityengine
var require_unityengine = __commonJS({
  "external-global-plugin:unityengine"(exports, module2) {
    module2.exports = CS.UnityEngine;
  }
});

// src/index.ts
var UnityEngine = __toESM(require_unityengine());
var import_unityengine = __toESM(require_unityengine());
console.log(
  CS.UnityEngine.Debug === UnityEngine.Debug,
  UnityEngine.Debug === import_unityengine.Debug
);

但是CS.UnityEngine要在访问CS.UnityEngine.Debug之后,才能在Object.getOwnPropertyNames里看到"Debug",所以经过__toESM处理之后导入的Debugundefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant