| name | extract-threejs-html-to-js |
| description | Extract Three.js logic from inline HTML script into a separate .js file, following the webgpu_lights_custom pattern. Use when the user asks to split HTML+Three.js, extract logic to JS, refactor inline script to module, or create a standalone .js for an examples HTML file. |
Extract Three.js HTML to Separate JS
將 HTML 中的 Three.js 內聯腳本抽出為獨立 JS 檔案,便於編輯器解析 bare imports(如 three/tsl)、代碼補全與維護。遵循 examples/webgpu_lights_custom.html + webgpu_lights_custom.js 的結構。
何時使用
- 用戶要求將 HTML 中的 three.js 邏輯抽出
- 用戶要求創建獨立的 .js 文件,類似 webgpu_lights_custom.js
- 用戶希望反覆執行此流程、建立可重用工作流
- 需要為 examples 目錄下的 HTML 示例做模塊化拆分
執行步驟
1. 讀取源 HTML
讀取目標 HTML 檔案,識別:
<script type="importmap"> — 保留在 HTML 中,瀏覽器依賴其解析 bare imports
<script type="module"> 內聯內容 — 要抽出的邏輯
- DOM 結構(
#info、#container、#c 等)— 保留在 HTML
2. 創建對應 .js 檔案
在同目錄下創建與 HTML 同名的 .js 檔案(如 webgpu_tsl_interoperability.html → webgpu_tsl_interoperability.js)。
檔案開頭註釋(必須保留):
內容規則:
- 將內聯腳本中的
import、變量聲明、函數定義、init() 調用全部移至 .js
- 保持原有縮進風格(與 examples 一致,使用 tab)
- 不修改任何業務邏輯
- 路徑相關:texture 等資源路徑保持相對 HTML 的路径(如
textures/planets/...),因 .js 由 HTML 載入,工作目錄以 HTML 為準
3. 修改 HTML
將內聯 <script type="module"> 替換為:
<script type="module" src="檔案名.js"></script>
例如:
<script type="module" src="webgpu_tsl_interoperability.js"></script>
保留在 HTML 中的內容:
importmap(完整保留)
- 所有 DOM 結構
- CSS 引用
- 僅保留上述一個
<script type="module" src="..."> 標籤
4. 驗證 jsconfig.json
若專案有 examples/jsconfig.json,確認其包含對 three、three/tsl、three/addons/ 等的映射,以便編輯器解析 .js 中的 bare imports。若無,可建議用戶新增。
5. 清單檢查
完成後確認:
參考範例
HTML 結構(webgpu_lights_custom.html):
<script type="importmap">
{ "imports": { "three": "...", "three/tsl": "...", "three/addons/": "..." } }
</script>
<script type="module" src="webgpu_lights_custom.js"></script>
JS 結構(webgpu_lights_custom.js):
- 頂部註釋說明拆分目的
- 完整 imports
- 類、變量、函數
- 末尾
init() 調用
注意事項
- 資源路徑:如
textureLoader.load('textures/...') 等路徑以 HTML 所在目錄為基準,無需改動
- canvas 引用:
document.getElementById('c') 等在 DOM 載入後執行,init() 由 init() 調用觸發,時序不變
- 可重複性:此流程可對任意
examples/*.html 重複執行,保持同一模式即可