vite-node初试
发布于 3 年前 作者 i5ting 3864 次浏览 来自 分享

特性

  • 开箱即用 ESM & TypeScript 支持 (possible for more with plugins)
  • Top-level await
  • Vite plugins, resolve, aliasing
  • Respect vite.config.ts
  • Shims for __dirname and __filename in ESM
  • Access to native node modules like fs, path, etc.
  • Watch mode (like nodemon) 此项未实现

测试vite-node的执行速度

简单测试一下,vite-node的执行速度

➜  vite-node git:(main) ✗ npm start index.ts
npm WARN npm npm does not support Node.js v15.14.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11, 12.
npm WARN npm You can find the latest version at https://nodejs.org/

> vite-node@0.0.5 start /Users/i5ting/workspace/github/vite-node
> DEBUG=vite-node:* node index.mjs "index.ts"

  vite-node:request //Users/i5ting/workspace/github/vite-node/index.ts +0ms
  vite-node:transform /@fs//Users/i5ting/workspace/github/vite-node/index.ts
const {
  performance,
  PerformanceObserver
} = require("perf_hooks");
console.log("hello vite-node");
for (var i in performance.nodeTiming) {
  console.log(i + " = " + performance.nodeTiming[i]);
}
 +0ms
hello vite-node
name = node
entryType = node
startTime = 0
duration = 357.889949798584
nodeStart = 2.457298994064331
v8Start = 3.4468069076538086
environment = 14.011312007904053
loopStart = 29.508057832717896
loopExit = -1
bootstrapComplete = 24.924965858459473
idleTime = 39.466068

注意

vite-node:request //Users/i5ting/workspace/github/vite-node/index.ts +0ms
vite-node:transform /@fs//Users/i5ting/workspace/github/vite-node/index.ts  +0ms

在请求和转换ts的时候,耗时0毫秒,这个速度还是非常赞的。

原理

  • 首先你需要理解vite原理,网上大把资料,参见 https://github.com/zhangyuang/vite-design
  • 遍历Node.js内置的builtinModules直接放到vite里
  • 在vite上下文里加入node自定义内容,比如require,__dirname,__filename等

问题

能否默认不出现vite.config.ts

内置在cli里,如果有vite.config.ts,做merge可能是比较好的做法。

引入vue别名看起来没啥用

package.json里没有依赖vue,而测试环境依赖了。并且在vite createServer里加了vue的alias,看起来是冗余代码。 ​

看起来__vite_ssr_import__也是多余。

debugTranform的时候,源码未分行

在index.mjs里,加一个换行就好了

 debugTransform(id, '\n' + result.code)

感兴趣的可以去蹭pr。 ​

使用的模块

debug大家都比较熟悉了,说3个略有差异的模块。 ​

minimist做cli解析

可圈可点,好处是足够小,从趋势和潮流上看我更喜欢clipanion。 ​

uvu测试

uvu是目前最小且最快的单测框架,我很喜欢,推荐。 ​

bumpp

发布版本的,作者自己Forked from version-bump-prompt,挺好用的。 ​

总结

从node最开始nan到n-api,都是支持其他语言扩展的。最开始是能用,现在追求好用,这代表node作为前端js基建已经很成熟了。 我的观点,esb或swc编译核心部分有性能慢的情况用合适方案替换是很好的,但不会被大量替换的。所以,现在看起来是其他语言替换js是趋势,但实际上,只是让js开发体验更好。按照之前社区经验,node实现有的模块是比c/c++快,所以不会都是c扩展,又怎么会有大量其他语言扩展呢? ​

你看到的其实是js越来越快,至于底层是rust,go,还是wasm都不重要,在应用层你用到的都是js,或ts。 趋势上看,还是非常好的。至于前端3.0能否颠覆,js都是最佳选择。另外,你真的写写其他语言,还是会觉得js真香。 Rails 尝鲜 Rails 7 的 esbuild,谈谈遇到的坑,其实node社区这种尝试更多。 黄一君说的很好,go和rust更多偏底层,而js偏应用层,注定不会有那么多偏底层的。 ​

ts-node还是有点慢,另一个方案vite-node,我感觉更靠谱一些,坐等它成长。 ​

2 回复

利用vite服务直接跑typescript代码?

回到顶部