在使用 react 的時候,很多時候在最初配置開發環境的時候,都直接使用 create-react-app 去建立已經自動配置好環境的 project。實在沒有太多的機會去自行配置這些工具,這篇文章就記錄學習這些工具時的一些筆記。
首先先看 gulp,在官方網頁上的描述是 "A toolkit to automate & enhance your workflow",我理解為一個工具可以自動化流程,所做的工作例如會有配合下面會提到的 babel 去 compile js,以及在開發的時候可以觀察檔案有沒有更動,如有的話就再做動作之類等等。
首先跟據這個 Quick Start 的教學 https://gulpjs.com/docs/en/getting-started/quick-start 做到可以在 command line 運行 gulp 進行一個什麼都不做的 task 。
(一)一個可以 copy file 的 gulp task
首先 project 之中創建一個新的資料夾 src,在裡面建立一個新的 index.html, 內容就大約是這樣
<html>
<head>
<title>Index</title>
</head>
<body>
Hello World!
</body>
</html>
然後提 gulpfile.js 更改成這樣
const gulp = require("gulp");
gulp.task("default", function () {
return gulp.src("src/*")
.pipe(gulp.dest("dist"));
});
運行 gulp 之後應該會得到以下的結果
PS C:\Sources\gulp-test> gulp
[09:38:17] Using gulpfile C:\Sources\gulp-test\gulpfile.js
[09:38:17] Starting 'default'...
[09:38:17] Finished 'default' after 28 ms
以及會發覺多了一個 dist 的 folder,裡面有的就是剛剛建立的 index.html。
這就是 gulp 的其中一個 API dest() 的使用,當然目前到輸出之間什麼都沒有做,所以看來兩邊輸入輸出都是一模一樣。
(二) 一個可以進行 babel 轉換的 gulp task
Babel 是一個 JavaScript 的編譯器,目的是就算是用新式的 javascript 寫的程式經過編譯後也可以在一些較舊瀏覽器上運行,例如:IE。至於有什麼新式的 javascript 會被轉換,這裡有一個網站 http://es6-features.org/ ,介紹了 es6 種種的增加的功能。
首先要用 npm 安裝 babel。
npm install --save-dev gulp-babel @babel/core
然後把 index.html 更改為這樣
<html>
<head>
<title>Index</title>
</head>
<body>
Hello World!
<div id="container"></div>
<script src="app.js"></script>
</body>
</html>
見到新增了一個 app.js 的文件,所以我們在同層之中新建一個 app.js ,內容如下:
class student {
constructor(name, subject){
this.name = name;
this.subject = subject;
}
}
let bob = new student("bob","math");
document.querySelector("#container").innerHTML = `Student Name: ${bob.name}, Subject: ${bob.subject}`;
在這個時候,如果直接用 chrome 開的話會見到到以下的結果:
而使用 IE 11 的話則會只顯示
這時,在 IE 11 按 F12 呼叫 Developer tool 的話,就會發覺 IE 11 有一個 Syntax error 的錯誤,正是 class 這個寫法未支援。
在這個時候回到 gulpfile.js, 更改成以下的模樣,也即時在 Babel 官網後按 Setup 後的 Usage (https://babeljs.io/setup#installation) 再加上一些更改:
const gulp = require("gulp");
const babel = require("gulp-babel");
gulp.task("default", function () {
gulp.src("src/index.html")
.pipe(gulp.dest("dist"));
return gulp.src("src/*.js")
.pipe(babel({
presets: ["@babel/preset-env"]
}))
.pipe(gulp.dest("dist"));
});
然後再在 command line 運行 gulp,這時在 dist 資料夾之中應該會有 app.js 和 index.html。使用 Chrome 直接開啟 index.html 還是會顯示:
再使用 IE11 去開啟 index.html, 就發現 IE11 也能顯示上述的字句了!
如果在這時打開 dist 的 app.js,就會發現下面的程式碼:
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var student = function student(name, subject) {
_classCallCheck(this, student);
this.name = name;
this.subject = subject;
};
var bob = new student("bob", "math");
document.querySelector("#container").innerHTML = "Student Name: ".concat(bob.name, ", Subject: ").concat(bob.subject);
就是透過 babel 造出這樣的轉換,使到舊式的瀏覽器也能運行最新的代碼。

