HBuilderX 运行 vite/vue3 cli项目解决esbuild依赖

💡
解决方案看文末

在 苹果芯片 Mac 系统上 HBuilderX 无法正常编译 vite/vue3 cli 项目, 提示

15:26:03.204 error during build:
15:26:03.204 Error:
15:26:03.208 You installed esbuild for another platform than the one you're currently using.
15:26:03.210 This won't work because esbuild is written with native code and needs to
15:26:03.213 install a platform-specific binary executable.
15:26:03.213 Specifically the "esbuild-darwin-arm64" package is present but this platform
15:26:03.216 needs the "esbuild-darwin-64" package instead. People often get into this
15:26:03.218 situation by installing esbuild with npm running inside of Rosetta 2 and then
15:26:03.224 trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
15:26:03.224 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
15:26:03.228 If you are installing with npm, you can try ensuring that both npm and node are
15:26:03.231 not running under Rosetta 2 and then reinstalling esbuild. This likely involves
15:26:03.234 changing how you installed npm and/or node. For example, installing node with
15:26:03.234 the universal installer here should work: https://nodejs.org/en/download/. Or
15:26:03.239 you could consider using yarn instead of npm which has built-in support for
15:26:03.239 installing a package on multiple platforms simultaneously.
15:26:03.242 If you are installing with yarn, you can try listing both "arm64" and "x64"
15:26:03.245 in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
15:26:03.246 https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
15:26:03.249 Keep in mind that this means multiple copies of esbuild will be present.
15:26:03.253 Another alternative is to use the "esbuild-wasm" package instead, which works
15:26:03.256 the same way on all platforms. But it comes with a heavy performance cost and
15:26:03.257 can sometimes be 10x slower than the "esbuild" package, so you may also not
15:26:03.260 want to do that.

这很奇怪, 在 外部Command-Line Interface模式下它是正常的。 但是在 HBuilderX 确不能编译。

几番查找下,只找到【报 Bug】HBuilderX mac M1 编译 vite/vue3 cli 项目时编译不了(hbx 运行编译)这样一篇帖子

尝试下, 上面这篇帖子的可以概括为修改将 esbuild-darwin-arm64 的包目录改成 esbuild-darwin-64

这个时候新的问题随之而来

Cannot start service: Host version "0.16.17" does not match binary version "0.14.42"

运行时提示版本号不对,需要使用对应的版本号。改用对应版本号后重新安装依赖,又遇到了提示最高可安装版本为0.15.18的问题,这实在是让人很为难。

经过一番搜索,我发现@esbuild/darwin-arm64这个包是最新的,而esbuild-darwin-arm64这个包的最后更新时间是 3 个月前。

15:30:18.775 项目 'my-vue3-project' 开始编译...
15:30:20.058 编译器版本:3.7.3(vue3)
15:30:20.067 请注意运行模式下,因日志输出、sourcemap 以及未压缩源码等原因,性能和包体积,均不及发行模式。
15:30:20.071 正在编译中...
15:30:42.645 项目 'my-vue3-project' 编译成功。
15:30:42.671 ready in 23228ms.
15:30:42.848 正在建立手机连接...
15:30:43.597 手机端调试基座版本号为3.6.18, 版本号相同,跳过基座更新
15:30:44.847 正在同步手机端程序文件...
15:30:50.518 同步手机端程序文件完成
15:30:51.582 正在启动HBuilder调试基座...

成功 ✌️!

如果你也遇到上述问题, 可直接安装@esbuild/darwin-arm64包,然后把node_modules/@esbuild/darwin-arm64这个目录复制一份名为node_modules/@esbuild/darwin-x64即可