用 Yarn + webpack 2 + Babel 架設 React 環境 « 關於網路那些事...
Webpack 是一個 module 整合工具,用來將javascript 打包成一支讓瀏覽器能夠執行的 bundle.js。
看似簡單,但其實功能非常強大
webpack 的功能:
- 和 Browserify一樣,可以整合 ES Modules, CommonJS 及 AMD modules,減少依賴進而加速了執行的時間
- 可以將js打包成單一個 bundle.js 或者多個可以非同步載入的模組(需搭配plugin,可減少初期載入時間)
- 可結合babel等編譯器,進行檔案預編譯功能。例如,將 JSX、ES6、Typescript...轉javascript,Handlebar 字串({{expression}}) 編譯,images 轉 Base64等
此外,還有一些 plugin 可以使用
【Yarn】
在這裡會使用 yarn 來做套件管理,
因為部分套件npm沒有提供,所以建議先配置好 yarn 環境
檢查是否安裝成功
【安裝 Webpack 】
首先,安裝webpack 所需要的一些依賴專案
這時會建立一個 yarn.lock
繼續,建立一個名稱為 webpack.config.js 的檔案,並輸入內容
webpack.config.js
【設定Babel 】
安裝 Babel 以及相關的依賴模組
建立名稱為 .babelrc 的檔案,並輸入內容
.babelrc
Babel可以幫我們處理JSX及ES6,翻譯成瀏覽器看得懂的語法
例如,下面兩段的語法,作用都會相同,但第一種的寫法,會讓我們更容易辨識
【建立 Clinet 檔案 】
建立一個 client 資料夾,並在資料夾內新增 index.html, index.js
./client/index.html
./client/index.js
【新增 html-webpack-plugin 】
html-webpack-plugin 主要是用來動態產生HTML內容,並且會自動將打包過的js整合再一起
安裝 html-webpack-plugin
接著開啟 webpack.config.js,加入新增的擴充,這裡會看到,我們將會把 client/index.html 作為模板
分別加入這些內容:
加入完成後,webpack.config.js內容如下:
webpack.config.js
【新增啟動及執行】
開啟 package.json,新增一個 script 以及加入 webpack-dev-server
新增後的 package.json如下:
package.json
【執行 webpack server】
由於剛剛在package script 我們已經將啟動webpack-dev-server的行為設定為名稱 start
因此,只要執行 yarn start 就可以啟動 webpack server
啟動完畢後,開啟 localhost:8080 並且開啟開發者模式,檢視console.log是否成功輸出 "Hey guys and ladies!!"
【React 淺入門】
接下來,我們準備來安裝React需要的依賴元件
接著新增一個 JSX 檔案,並且依照Pascal Case 命名規則,將檔名第一字母大寫,副檔名則可以是jsx或js,建議使用 jsx
在 client 資料夾 新增一個 components/App.jsx
client/index.html
client/index.js
client/components/App.jsx
接著執行 yarn start,迎接第一個 Hello world~
## 【參考資源】 本文根據 Joy Warugu 的文章進行整理而成, 文章位置: https://scotch.io/tutorials/setup-a-react-environment-using-webpack-and-babel如果你喜歡我們的文章內容,請在這裡按個讚
Tweet