什麼是 Compile-to-JS?

About JS dialects

R4 Cheng
4 min readOct 26, 2020

It’s better to describe the process “compile” as “transpilation.” — Tom from Stack Overflow

結論:Compile-to-JS 是將衍伸的語言 (e.g. TypeScript) transpilate 回 JavaScript

=> 你只要嘗試用 TypeScript 寫一個簡單的專案就能了解其意思

JavaScript 總是在特定的環境中執行:在 Chrome 和 Electron 中,它是 V8 engine ,在 Firefox 中,它是 SpiderMonkey 。這些引擎中的每一個都會有它專門支持的 language features,其他引擎卻不支持。例如,某些引擎僅支持 var 而不支持 constlet ,一些支持 async/await ,而另一些僅支持 Promise

然而,Web 開發人員想在他使用的引擎上實現所有 language features ,即便這個引擎不支持這些 features。為什麼?大多數新的 language features 是為了將複雜的概念以更簡單,更簡潔的方式表達。因為 code 的首要任務是明確其目標。

例如: A transpiler like Babel 依靠一種稱為 abstract syntax tree 的 intermediate representation (中間表示?)。it can read a script written using advanced syntax, and then re-express the script using a restricted set of language features.

換言之,即使我們使用不同且更被廣泛支持的其它語言來編寫程式,它也可以產生功能上等效的 code 。

回到主題,所以什麼是 Compile-to-JS?

這是用字不精確的問題! 根據 Tom 的說法: Perhaps we web developers have gotten lazy in our terminology. When we talk of “compiling” JavaScript, we are not usually talking about converting the script to something like bytecode. We’re talking about transpilation.

也就是說前端世界的 compile 是將衍伸的語言 (e.g. TypeScript) transpilate 回 JavaScript

使用 HTMLCSSJavaScript 構建一個網頁依然是網頁開發的核心。但是現今,大多數嚴謹的應用程序幾乎是全 JavaScript (或類似的東西) + SASS 構成,因此當我們要 Building the application 時,必須將 source code 轉換為這三種基本語言。

我們將所有這些過程統稱為 compile。

TypeScript vs. JavaScript

  • 只是 JavaScript 的衍伸,可以完全將 code 轉換回 JavaScript
  • 比 JavaScript 更容易 debug (因為 JS 是dynamic type ,TS 解決了此問題)
E.g.tsc example.ts // transpilate example.ts to JS
=> example.js // yield JS file

Reference

[1] https://stackoverflow.com/questions/48134900/what-do-those-javascript-front-end-build-tools-mean-when-they-say-compile-my-j?answertab=votes#tab-top

[2] What is TypeScript and Should You Learn it? https://www.youtube.com/watch?v=i43W0XSiuIE

Sign up to discover human stories that deepen your understanding of the world.

--

--

R4 Cheng
R4 Cheng

Written by R4 Cheng

「0」が過去で「1」が未来「今」は何処にもない

No responses yet

Write a response