iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0

昨天寫完自動編碼,不知道大家有沒有感覺到:每次寫完都要再重新上傳 JS 檔,有夠麻煩,這什麼爛開發體驗!

所以這篇文章我們來建置一個開發環境,這樣就不用每次都要重新上傳檔案,不過在這之前我們要知道以下兩個重點...

  • kintone 不能使用 ESmodule
  • 上傳的網址必須是要 https 開頭。

關於不能使用 ESmodule 這點,我也覺得有夠雷,但沒辦法...既然系統不給用,只好換個方法。

Rsbuild 是什麼?

Rsbuild 官網: https://rsbuild.dev/

官網介紹:Rsbuild 是由 Rspack 驅動的高性能構建工具,它默認包含了一套精心設計的構建配置,提供開箱即用的開發體驗,並能夠充分發揮出 Rspack 的性能優勢。Rsbuild 是與 Vite、Create React App 或 Vue CLI 處於同一層級的構建工具,它們都默認包含了開發服務器、命令行工具和合理的構建配置,以此來提供開箱即用的體驗。

我們會使用 Rsbuild 來建立開發環境,你可能會問為什麼不使用 Vite 或是 Webpack 就好了?原因是因為 kintone 不給用 ESmodule,所以不考慮 Vite,然後 Webpack 又要自己配,稍嫌麻煩了點,所以使用 Rsbuild。

當然你也可以在 Vite 中使用 build --watch 搭配 preview,透過不斷打包的方式,不過多放幾個較肥的套件,速度就會慢下來。

環境建置

首先跟著官網下指令:

npm create rsbuild@latest

然後選擇自己想要的框架,目前提供的有以下:

  • react / react-ts
  • vue3 / vue3-ts
  • vue2 / vue2-ts
  • lit / lit-ts
  • preact / preact-ts
  • svelte / svelte-ts
  • solid / solid-ts
  • vanilla / vanilla-ts

我這邊選擇原生 JS 當作範例。

rsbuild.config 設定

首先開啟設定檔 rsbuild.config,因為在編譯的時候會把檔案變成很多個 chunk,我們希望它最終只會產出一個檔案就好,因此增加以下在設定檔案中的 defineConfig

performance: {
  chunkSplit: {
    strategy: "all-in-one",
  },
},

會希望只有一個的原因是等等要上傳 URL 的時候不用上傳很多個,如果你想要分多個 chunk 避免單一檔案太大,這部分可以自行處理。

安裝 @rsbuild/plugin-basic-ssl

上面有提到需要 https,所以安裝 @rsbuild/plugin-basic-ssl 並引入:

npm add @rsbuild/plugin-basic-ssl -D

接著放到

import { defineConfig } from '@rsbuild/core'
import { pluginBasicSsl } from '@rsbuild/plugin-basic-ssl' // 新增這行

export default defineConfig({
  plugins: [pluginBasicSsl()], // 新增 plugin

修改 output 路徑

修改成以下後,打開網址 https://localhost:3000/app.js 就會看到內容了,再把這段網址丟到 kintone 後台中即可。

output: {
  distPath: {
    js: './',
  },
  filename: {
    js: 'app.js'
  },
}

關掉熱更新

defineConfig 中把熱更新關掉:

  dev: {
    hmr: false,
    liveReload: false,
  }

完整的設定檔會像是以下:

import { defineConfig } from '@rsbuild/core'
import { pluginBasicSsl } from '@rsbuild/plugin-basic-ssl'

export default defineConfig({
  plugins: [pluginBasicSsl()],
  output: {
    injectStyles: true,
    distPath: {
      js: './',
    },
    filename: {
      js: 'app.js',
    },
  },
  performance: {
    chunkSplit: {
      strategy: 'all-in-one',
    },
  },
  dev: {
    hmr: false,
    liveReload: false,
  }
})

調整 src/index.js

記得要改一下檔案,才看得出變化,所以我們在 index.js 編輯一下:

kintone.events.on('app.record.index.show', (event) => {
  const el =  kintone.app.getHeaderSpaceElement()
  el.textContent = 'Hello kintone!!'
})

把 URL 貼到 kintone 後台

最後一個步驟了,我們打開 kintone 並進入目標的應用程式,點選 設定 > 透過JavaScript/CSS自訂 把剛剛的 https://localhost:3000/app.js 貼上去,如果手機版要用的話,下面記得也要貼。

這樣上傳 URL 以後就會出現 Hello kintone!! 的字樣在應用程式首頁了!

好麻煩喔...有範例嗎?

你們的聲音我已經聽到了,所以我把範例上傳到 Github 上了:

Github Repo:https://github.com/daniel003051/kintone-vanilla-js

當然設定還有很多地方可以調整,也不一定要使用 Rsbuild 來開發,這完全依照開發者個人需求來調整就可以了!


上一篇
Day 04 | 小試身手之「自動編碼」篇
下一篇
Day 06 | 上傳好幫手:kintone-customize-uploader
系列文
我阿嬤都會的 kintone 客製化開發13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言