alibaba / pont

🌉数据服务层解决方案
MIT License
3.03k stars 254 forks source link

pont无法在vite3.0中使用 #330

Closed Lruler closed 1 year ago

Lruler commented 2 years ago

What happens(发生了什么)?

新建vite3.0 的react项目中使用pont报错 package.json

image

报错信息

Error: Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/lruler/Desktop/vite-project/pontTemplate970.js from /Users/lruler/Library/pnpm/global/5/.pnpm/pont-engine@1.3.3/node_modules/pont-engine/lib/utils.js not supported. pontTemplate970.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead rename pontTemplate970.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /Users/lruler/Desktop/vite-project/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

image

可能和 #327 中提到的vite只支持esm有关?

我另外在vite的2.9.1测试过可以正常使用pont

bluryar commented 2 years ago

node的特性,假如最近的package.json声明了type:"module", node就会按照ESM去解析, 此后commonjs的模块需要显性命名后缀:“.cjs”,而 https://github.com/alibaba/pont/blob/master/packages/pont-engine/src/utils.ts#L367 这里在生成临时文件的时候没有去检查用户的package.json的配置(实际情况可能需要考虑更多配置的写法)。 或许朋友们可以尝试提个PR去给pont-config.json加个配置项:moduleResolution: 'cjs' | 'esm'


这时候我觉得利用pnpm的workspace将pont生成出来的接口文件作为一个单独的分包。 这样的话,你无需将整个项目都声明成ESModule, 可单独的声明pont相关的包的package.json为type:commonjs.

这里假设你和我一般怠惰:用的默认配置,一旦项目接口多了以后,生成的mods数量大约是个成百上千的规模吧,根据vite的特性,需要发送同等数量或者更多的http请求,假如配置的还是 surrounding: typeScript ,vite还要转换ts,再经过内部的文件转换服务(这里瞎说的,hh), 最终的结果就是:每次刷新会有近10s的白屏(仅在开发环境)。

故此,一个可能的建议是:单独构建一个子包: 导出生成的接口或者如pont建议的那般挂载到window对象上,然后导出根据项目需要封装过的axiosfetch或者其他请求函数,在子包中新增一个新的vite.config.ts去单独配置, 然后使用vite去构建库。


另外一个解决问题的思路是:配置pont,不再将mods挂载到window下, 单独引入接口文件使用。 这很麻烦, 但也许我们可以通过antfu的 unplugin-auto-import 包去做到自动引入,同时又避免因为在项目入口直接全量引入导致的首屏加载缓慢的问题。


目前我只测试了第一个方案,原来接近1700个http请求可以降低到500个左右(项目其他模块),首屏加载从15s到了3s。

ianfuin commented 2 years ago

可试下 1.4.0 版本

Garthguo commented 1 year ago

你解决了吗