簡易入門 Snowpack + React + Typescript,享受原生支援 Typescript 的快樂 !
      前言
承接上一篇知識分享,這次我們要分享 Snowpack + React + Typescript 的設定流程。完整的專案,這次我有打包放在 GitHub,程式碼參考 Snowpack Template,只保留所有關於Typescirpt的設定及加上了一些演示代碼。
Snowpack提供原生的 Typescript 支援,Snowpack 可以直接建置 Typescript 代碼並進行優化,這樣節省了開發者們需多寶貴的時間。
廢話不多說,讓我們看看要怎麼著手。
首先
我們可以利用 Snowpack 提供的工具來起始我們的專案,使用 @snowpack/app-template-minimal template :
npx create-snowpack-app snowpack-typescript-react --template @snowpack/app-template-minimal
我們需要安裝兩個 dependencies :
npm install react react-dom
因為 Typescript 的原故,這次我們要安裝的 dev-dependencies 相對的比較多,表列如下:
- typescript (主角)
 - @snowpack/plugin-dotenv (支援 .env 讀取)
 - @snowpack/plugin-react-refresh (支援 Hot Module Replacement)
 - @snowpack/plugin-typescript (支援 Typescript 的型別檢查)
 - @types/react
 - @types/react-dom
 - @types/snowpack-env (Snowpack module 的 Types)
 
npm install --save-dev typescript @snowpack/plugin-dotenv @snowpack/plugin-react-refresh @snowpack/plugin-typescript @types/react @types/react-dom @types/snowpack-env
安裝完後,就可以開始設置專案啦 !
設置
我們會修改 snowpack.config.js 如下:
module.exports = {
  mount: {
    public: { url: '/', static: true },
    src: { url: '/dist' },
  },
  plugins: [
    "@snowpack/plugin-dotenv",
    "@snowpack/plugin-react-refresh",
    "@snowpack/plugin-typescript",
  ],
};
首先你需要創建 src 跟 public 資料夾,然後我們會把 index.css 和 index.html 檔案丟到 新建的 public 資料夾,index.js 則會改名成 index.tsx 並移到 src 資料夾內。
接著我們修改一下 index.html 檔案,在 <body> tag 裡面加入 <div id="root"></div>,並更新<script> tag 成 <script type="module" src="/dist/index.js"></script> ,最後如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="description" content="" /> <link rel="stylesheet" type="text/css" href="/index.css" /> <title></title> </head> <body> <div id='root'></div> <noscript>You need to enable JavaScript to run this app </noscript> <script type="module" src="/dist/index.js"></script> </body> </html>
如果想要知道這麼改動的原因可以參考官方網站,也可以參考上一篇。
接著我們可以幫我們的 index.jsx 檔案,加入以下代碼 :
import React from "react";
import ReactDOM from "react-dom";
ReactDOM.render(
  <React.StrictMode>
    <div> hello world </div>
  </React.StrictMode>,
  document.getElementById("root") as HTMLElement
);
// Hot Module Replacement
if (import.meta.hot) {
  import.meta.hot.accept();
}
並搭配以下的 tsconfig.json :
{
  "include": ["src", "types"],
  "compilerOptions": {
    "module": "esnext",
    "target": "esnext",
    "moduleResolution": "node",
    "jsx": "preserve",
    "baseUrl": "./",
    "noEmit": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "importsNotUsedAsValues": "error"
  }
}
現在可以跑跑看囉 !
npm start
運行畫面如下:
      然後接著運行 :
npm run build
你的 build 資料夾,結構應該如下:
      恭喜你 ! 一切已經準備就緒,你可以開始開發你的 React Typescript 專案,就是這麼簡單。如果嫌麻煩,可以試試以下的代碼:
// .env file // 需要在變數前加上 SNOWPACK_PUBLIC_ ,不然不會加入環境變數中 SNOWPACK_PUBLIC_GUEST_NAME=Happy Tiger
// index.tsx
import React from "react";
import ReactDOM from "react-dom";
import App from "./app";
// 獲取環境變數
const GUEST_NAME = import.meta.env.SNOWPACK_PUBLIC_GUEST_NAME;
ReactDOM.render(
  // Strict Mode is a tool for highlighting potential problems in React code.
  <React.StrictMode>
    <App guestName={GUEST_NAME} />
  </React.StrictMode>,
  document.getElementById("root") as HTMLElement
);
// Hot Module Replacement
if (import.meta.hot) {
  import.meta.hot.accept();
}
在 src 加入新檔案 app.tsx :
import React, { useState, useEffect } from "react";
interface AppProps {
  guestName?: string;
}
const App: React.FunctionComponent<AppProps> = ({
  guestName = "Customer",
}: AppProps) => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    const timer = setTimeout(() => setCount(count + 1), 1000);
    return () => clearTimeout(timer);
  }, [count, setCount]);
  return (
    <div>
      {`Time since start: ${count}`}
      <div>{`Welcome to React App ${guestName} !`}</div>
    </div>
  );
};
export default App;
完成變更後的運行畫面應該如下:
      我自己對 Snowpack 可謂是愛不釋手,這個工具很大程度節省了建置的時間,讓碼農可以專心務農。希望看完這篇文章的你可以有所收穫。
Happy Coding !
Reference:
- https://github.com/snowpackjs/snowpack/tree/main/create-snowpack-app/app-template-react-typescript
 
