Vite 运行 TypeScript 文件原理剖析 All In One
Vanilla + TypeScript
# create project
$ yarn create vite
# install
$ yarn
# dev
$ yarn dev
ESM
import './style.css'
const app = document.querySelector<HTMLDivElement>('#app')!
app.innerHTML = `
<h1>Hello Vite!</h1>
<a href="https://vitejs.dev/guide/features.html" target="_blank">Documentation</a>
`
interface Human {
name: string;
}
class Person implements Human {
name: string;
constructor(name: string) {
this.name = name;
}
getName() {
console.log('name', this.name);
}
}
const person:Person = new Person('xgqfrms');
person.getName();
person.name;
Vite 处理后, ts => js ✅
浏览器直接访问 HTTP Server ❌
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "video/mp2t".
Strict MIME type checking is enforced for module scripts per HTML spec.
实现原理剖析
Vite 天然支持引入 .ts
文件。
Vite 仅执行 .ts
文件的转译
工作,并不执行任何类型检查
。
Vite 使用 esbuild
将 TypeScript
转译到 JavaScript
,约是 tsc
速度的 20~30 倍,同时 HMR
更新反映到浏览器的时间小于 50ms。
NPM 依赖解析和预构建
依赖预构建
请求转发: 请求 ts 返回 js
refs
https://cn.vitejs.dev/guide/features.html#typescript
https://cn.vitejs.dev/guide/migration.html
https://juejin.cn/post/7060673531389935653
https://juejin.cn/post/7064853960636989454
https://juejin.cn/post/6937847568114122760
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 ️,侵权必究⚠️!