on
스트림라이트 사용자 지정 구성 요소 + Vite + 바닐라 JS
스트림라이트 사용자 지정 구성 요소 + Vite + 바닐라 JS
바닐라 JS를 기반으로 구성 요소 생성
템플릿 폴더에서
vite를 사용하여 새 구성 요소를 생성하고 구성 요소를 테스트하기 위한 init.py 코드를 추가합니다.
$ mkdir vite_vanilla_component $ cd vite_vanilla_component $ npm init vite@latest frontend --template vanilla # npm v6 (v7 is different) $ touch __init__.py # command may be different in Windows
아래 init.py 코드를 추가하세요.
import os import streamlit.components.v1 as components _RELEASE = False if not _RELEASE: _component_func = components.declare_component( "vite_vanilla_component", url="http://localhost:3000", # vite dev server port ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/dist") _component_func = components.declare_component("vite_vanilla_component", path=build_dir) def my_component(name, key=None): component_value = _component_func(name=name, key=key, default=0) return component_value if not _RELEASE: import streamlit as st st.subheader("Component Test") num_clicks = my_component(name = "NameViteVanilla") st.markdown("You've clicked %s times!" % int(num_clicks))
프런트엔드 노드 라이브러리 설치, streamlit-component-lib, vite.config.js 생성
$ cd frontend $ npm i $ npm i streamlit-component-lib $ touch vite.config.js
vite.config.js는 다음과 같아야 합니다.
export default { base: './' }
main.js의 내용을 다음과 같이 대체한다(원래 구성 요소-리포의 무반응에 기초함).
import { Streamlit } from "streamlit-component-lib" const span = document.body.appendChild(document.createElement("span")) const textNode = span.appendChild(document.createTextNode("")) const button = span.appendChild(document.createElement("button")) button.textContent = "Click Me!" let numClicks = 0 let isFocused = false button.onclick = function() { numClicks += 1 Streamlit.setComponentValue(numClicks) } button.onfocus = function() { isFocused = true } button.onblur = function() { isFocused = false } function onRender(event) { const data = event.detail if (data.theme) { const borderStyling = `1px solid var(${ isFocused ? "--primary-color" : "gray" })` button.style.border = borderStyling button.style.outline = borderStyling } button.disabled = data.disabled let name = data.args["name"] textNode.textContent = `Hello, ${name}! ` + String.fromCharCode(160) Streamlit.setFrameHeight() } Streamlit.events.addEventListener(Streamlit.RENDER_EVENT, onRender) Streamlit.setComponentReady() Streamlit.setFrameHeight()
예제 실행
기본 디렉토리에서 프런트엔드로 이동하여 개발 서버에서 서비스합니다.
$ cd template/vite_vanilla_component/frontend $ npm run dev
기본 디렉토리에서 별도의 터미널에서 스트림라이트 앱을 탐색하여 실행합니다(파이썬 환경이 활성화되었다고 가정).
$ cd template $ streamlit run vite_vanilla_component/__init__.py # run the example
아래 이미지를 보고 버튼을 클릭하면 카운트가 증가합니다.
구성 요소가 잘려 보입니다. 이 문제를 해결하려면 구성요소의 본문 스타일을 여백: 0;으로 설정하십시오.
from http://gong-tech.tistory.com/42 by ccl(A) rewrite - 2021-09-24 12:00:32