One item that we did not touch upon is how to compile all of the React/TypeScript code (plus every dependency installed with npm), into a single folder with plain HTML/CSS/JS code. Such output can then be shared with other people and rendered by the browser without the need of a build toolchain.
In this instance, we use Babel to compile to JS code and Webpack (configured by create-react-app) for serving the component and bundling into a single folder. We could run Parcel and Rollup as Webpack alternatives in a new Streamlit Component template.
The _component_func
returned by declare_component
accepts a path
argument instead of url
, which loads frontend code from files in the given path instead of from a webserver. Your npm project can run the command npm run build
to build all the frontend code in production mode (and optimized for the best performance) into the frontend/build/
folder. The path
argument can be used in the declaration of the component in the __init__.py
file to point to the optimized build/
folder:
import streamlit.components.v1 as components
# Define location of the packaged frontend build
parent_dir = os.path.dirname(os.path.abspath(__file__))
build_dir = os.path.join(parent_dir, "frontend/build")
_component_func = components.declare_component(
"custom_slider",
path=build_dir # Change how to access component by path instead of url
)
You lose the hot-reloading from a running Webpack server, but now your app should work with a single streamlit run app.py
command! Also, other users will be able to use this build/
folder in Streamlit without having to install a frontend build toolchain to understand the fancy Typescript.
Instead of using an external web server to deliver the component, you can now bundle the compiled frontend code into your Python package. The command python setup.py bdist_wheel --universal
will build the Python package as a wheel file, and include the build/
folder inside as defined by the MANIFEST.in
file of the template (don’t forget to include the name of the package in the MANIFEST.in
file). You can then share this wheel file to others or even upload it to PyPi.
Be sure to check out the Streamlit docs for a tutorial on uploading to PyPi.