Skip to content
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

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

Open
xtutu opened this issue Sep 11, 2024 · 2 comments
Open

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

xtutu opened this issue Sep 11, 2024 · 2 comments

Comments

@xtutu
Copy link
Contributor

xtutu commented Sep 11, 2024

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'
@chexiongsheng
Copy link
Collaborator

chexiongsheng commented Sep 11, 2024

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

@xtutu
Copy link
Contributor Author

xtutu commented Sep 12, 2024

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

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

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

2 participants