puerts icon indicating copy to clipboard operation
puerts copied to clipboard

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

Open xtutu opened this issue 1 year 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

你搞混了概念:1、运行环境是否支持esm;2、模块是否支持esm; fs或者buffer是nodejs的原生模块,这原生模块支不支持esm是取决于该版本nodejs。和v8或者nodejs集成的v8支不支持esm是两码事。 即使是纯js实现的模块,模块本身支不支持esm也是取决于这模块本身,和它用什么虚拟机环境加载没关。

chexiongsheng avatar Sep 11 '24 12:09 chexiongsheng

这两个模块,在原生的 nodejs 16 里,只要把 package.json 中设置: "type": "module", 就可以用 esm 方式来加载。

不知道 puerts 中,是否也有类似的设置入口? @chexiongsheng

xtutu avatar Sep 12 '24 02:09 xtutu