添加扩展#
JupyterLite 重复使用与 JupyterLab 3.0+ 相同的预构建扩展系统。预构建扩展有时也称为联邦扩展。在 JupyterLab 中,它们可以通过 pip
和 conda
安装,而无需重新构建整个 JupyterLab 应用程序。
JupyterLite 默认附带的所有应用程序均使用 JupyterLab 组件构建。这使得大多数现有的第三方 JupyterLab 扩展也能与 JupyterLite 兼容。
从环境中添加新扩展#
创建新环境#
添加新扩展的最简单方法是在已安装扩展的 Python 环境中使用 JupyterLite CLI。
您可以选择您喜欢的工具来管理这些依赖项,例如 pip
、conda
或 mamba
。对于 conda
和 mamba
,它们通常在 environment.yml
中定义,对于 pip
,则在 requirements.txt
中定义。
如果您想在本地机器上构建 JupyterLite 网站,最好先创建一个新环境。
这可以使用 venv
模块完成
python -m venv .
source bin/activate
或使用 conda
/ mamba
mamba create -n my-jupyterlite-deployment -c conda-forge python -y
mamba activate my-jupyterlite-deployment
在环境中安装扩展#
例如,我们使用以下 requirements.txt
jupyterlab-tour
jupyterlab-night
此文件列出了两个扩展,其中一个是主题。运行以下命令安装它们
python -m pip install -r requirements.txt
如果您已安装 jupyterlab
,您可以使用以下命令验证它们是否正确安装
jupyter labextension list
这应该会返回类似以下内容
JupyterLab v4.*.*
PREFIX/share/jupyter/labextensions
jupyterlab-tour v4.0.1 enabled OK
jupyterlab-night v0.4.0 enabled OK
构建 JupyterLite 网站#
现在我们需要生成将包含这些扩展的 JupyterLite 存档。这可以通过以下命令完成
jupyter lite build
当您运行 jupyter lite build
时,JupyterLab 环境中的所有预构建扩展,例如 {sys.prefix}/share/jupyter/labextensions
将被
复制到
{output-dir}/extensions
将其主题信息复制到
{output-dir}/{app/?}theme/
Jupyter Widgets 和自定义渲染器的情况#
一些扩展,例如 Jupyter Widgets 和自定义渲染器,在与笔记本一起工作时,还需要在运行时安装一个 Python 包。例如,ipyleaflet
、bqplot
或 plotly
就是这种情况。
要安装前端扩展,只需将其添加到需求列表中。例如,继续上面定义的 requirements.txt
文件
jupyterlab-tour
jupyterlab-night
ipywidgets
bqplot
plotly
您的 JupyterLite 实例的最终用户仍然需要在运行时使用 IPython 兼容的 %pip
magic 在他们的笔记本中安装依赖项
%pip install -q ipywidgets bqplot plotly
这等同于
import piplite
await piplite.install(["ipywidgets", "bqplot", "plotly"])
避免前端扩展和 Python 包之间的版本漂移#
在某些情况下,通过 %pip install
或 piplite.install
在运行时安装的包版本可能不再与部署的前端扩展兼容。例如,当 JupyterLite 网站在几周前构建和部署,并且此后发布了新版本的 Python 包时,可能会发生这种情况。在这种情况下,前端扩展尚未更新,因为它们仍然作为部署的一部分以静态文件形式提供。
避免这种不匹配的一种方法是更明确地固定依赖项。例如
ipywidgets==7.7.0
bqplot==0.12.30
plotly==5.8.0
笔记本中面向用户的代码也必须使用相同的版本才能保持兼容性
%pip install -q "ipywidgets==7.7.0" "bqplot==0.12.30" "plotly==5.8.0"
这等同于
import piplite
await piplite.install(["ipywidgets==7.7.0", "bqplot==0.12.30", "plotly==5.8.0"])
这有点脆弱,但目前可以解决问题。未来版本的 JupyterLite 有望改进这一点。
如果您想更好地控制依赖项,请查看 配置 piplite URL 的指南。
如何判断扩展是否与 JupyterLite 兼容?#
对于可能兼容的扩展,一个很好的起点是 JupyterLab 问题 Extension Compatibility with 3.0 (#9461)。此外,本网站还展示了一些 扩展。
高级扩展配置#
如果您正在寻找更多配置扩展的选项,请查看关于 高级扩展配置 的专用指南。