iT邦幫忙

2021 iThome 鐵人賽

DAY 23
0
Modern Web

Web Component 網頁元件之路系列 第 23

[Day23] - 介紹 Stencil.js 如何使用

今天我們來介紹一下 , 昨天說明的 Web Component 框架中的其中之一 - stencil.js

特別拿出來介紹 , 是因為如果你想要用 TypeScript 來管理你的 Web Component ,

Stencil.js 是一個不錯的選擇

Stencil.js

stencil.js LOGO

內文

one 利用 Stencil Cli 建立 Stencil 的新專案

npm init stencil

two 觀察專案內容

當你利用 Stencil Cli 建立新專案後 , 它會幫你產生如下結構的專案內容

test-comp
├── .editorconfig
├── .gitignore
├── .prettierrc.json
├── LICENSE
├── package-lock.json
├── package.json
├── readme.md
├── src
│   ├── components
│   │   └── my-component
│   │       ├── my-component.css
│   │       ├── my-component.tsx
│   │       └── readme.md
│   ├── components.d.ts
│   ├── index.html
│   ├── index.ts
│   └── utils
│       ├── utils.spec.ts
│       └── utils.ts
├── stencil.config.ts
└── tsconfig.json

我們可以發現有一個 src/components 的資料夾 , 那就是我們放 Web Component 的地方

three 利用 stencil build 建立 Web Component

npm run build

我們可以看到多出一個 www/build 的資料夾

將資料夾中的所有檔案 copy 出來

four 引用建立出來的 Web Component

利用 script 引入 [專案名稱].js[專案名稱].esm.js 這兩個檔案

<script type="module" src="./test-comp.esm.js"></script>
<script nomodule="" src="./test-comp.js"></script>

我們就可以在 html 中使用我們產出的 web component

<!doctype html>
<html dir="ltr" lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
  <title>Stencil Component Starter</title>
  <script type="module" src="./test-comp.esm.js"></script>
  <script nomodule="" src="./test-comp.js"></script>
</head>
<body>
<my-component first="Stencil" last="'Don't call me a framework' JS"></my-component>
</body>
</html>

上一篇
[Day22] - 介紹 LitElement 如何使用
下一篇
[Day24] - 介紹 Svelte.js 如何使用
系列文
Web Component 網頁元件之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
lagagain
iT邦新手 2 級 ‧ 2021-09-28 06:39:55

哈哈/images/emoticon/emoticon38.gif

Tree iT邦新手 3 級 ‧ 2021-09-28 09:50:43 檢舉

昨晚太累 /images/emoticon/emoticon20.gif

內容候補 /images/emoticon/emoticon16.gif

Tree iT邦新手 3 級 ‧ 2021-10-01 14:19:36 檢舉

內容補上拉 /images/emoticon/emoticon37.gif

我要留言

立即登入留言