puerts icon indicating copy to clipboard operation
puerts copied to clipboard

[Unity] v8 和 nodejs 加载 js 模块的行为不一致

Open xtutu opened this issue 5 months ago • 2 comments

detail | 详细描述

Node 版本似乎只支持 CommonJS,不支持 ESM

之前用的 puerts v8 2.1.0 版本 , 逻辑代码用 TypeScript 编写, 所有代码打包成一个 init.mjs 文件。 编译输出为 ESM 格式 可以正常运行。

puerts 版本 切换为 node 2.1.0 , 引入了一些 nodejs 的库后,出现下面的情况:

  1. 采用 Import 方式引入其他库,编译输出为 ESM报错
import * as fs from "fs"  
// 调用 fs.writeFileSync
// 提示: fs.writeFileSync is not a function

 import { Buffer } from 'node:buffer'
// 提示: The requested module 'node:buffer' does not provide an export named 'Buffer'
  1. 改为 require 方式引用, 编译输出为 ESM 。 可以正常运行
let fs = require("fs")  
let Buffer = require('node:buffer').Buffer 
  1. 用 import 方式引用,编译输出为 CommonJS , 可以正常运行
import * as fs from "fs"  
import { Buffer } from 'node:buffer'

xtutu avatar Sep 11 '24 10:09 xtutu