extension_dev.rst 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. .. _developer_extensions:
  2. Extension Developer Guide
  3. =========================
  4. The JupyterLab application is comprised of a core application object and a set of extensions. JupyterLab extensions provide nearly every function in JupyterLab, including notebooks, document editors and viewers, code consoles, terminals, themes, the file browser, contextual help system, debugger, and settings editor. Extensions even provide more fundamental parts of the application, such as the menu system, status bar, and the underlying communication mechanism with the server.
  5. A JupyterLab extension is a package that contains a number of JupyterLab plugins. We will discuss how to write a plugin, then how to package together a set of plugins into a JupyterLab extension.
  6. Other resources
  7. ---------------
  8. Before we get started, here are some resources for hands-on practice or more in-depth reference documentation.
  9. Tutorials
  10. ^^^^^^^^^
  11. We provide a set of guides to get started writing extensions for JupyterLab:
  12. - :ref:`extension_tutorial`: A tutorial to learn how to make a simple JupyterLab extension.
  13. - The `JupyterLab Extension Examples Repository <https://github.com/jupyterlab/extension-examples>`_: A short tutorial series to learn how to develop extensions for JupyterLab by example.
  14. - :ref:`developer-extension-points`: A list of the most common JupyterLab extension points.
  15. - Another common pattern for extending JupyterLab document widgets with application plugins is covered in :ref:`documents`.
  16. Cookiecutters
  17. ^^^^^^^^^^^^^
  18. We provide several cookiecutters to create JupyterLab extensions:
  19. - `extension-cookiecutter-ts <https://github.com/jupyterlab/extension-cookiecutter-ts>`_: Create a JupyterLab extension in TypeScript
  20. - `extension-cookiecutter-js <https://github.com/jupyterlab/extension-cookiecutter-js>`_: Create a JupyterLab extension in JavaScript
  21. - `mimerender-cookiecutter-ts <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`_: Create a MIME Renderer JupyterLab extension in TypeScript
  22. - `theme-cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`_: Create a theme extension for JupyterLab
  23. API Reference Documentation
  24. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  25. Here is some autogenerated API documentation for JupyterLab and Lumino packages:
  26. - `JupyterLab API Documentation <https://jupyterlab.github.io/jupyterlab/>`_
  27. - `Lumino API Documentation <https://jupyterlab.github.io/lumino/>`_
  28. Overview of Extensions
  29. ----------------------
  30. A JupyterLab extension is a package that contains JupyterLab plugins. A plugin is the basic unit of extensibility in JupyterLab. An extension is a package that contains one or more JupyterLab plugins. There are several types of extensions:
  31. - A *source extension* is a JavaScript (npm) package that exports one or more plugins. Installing a source extension requires a user to rebuild JupyterLab. This rebuilding step requires Node.js and may take a lot of time and memory, so some users may not be able to install a source extension. However, the total size of the JupyterLab code delivered to a user's browser may be reduced compared to using prebuilt extensions. See :ref:`deduplication` for the technical reasons for rebuilding JupyterLab when a source extension is installed.
  32. - A *prebuilt extension* (new in JupyterLab 3.0) distributes a bundle of JavaScript code prebuilt from a source extension that can be loaded into JupyterLab without rebuilding JupyterLab. In this case, the extension developer uses tools provided by JupyterLab to compile a source extension into a JavaScript bundle that includes the non-JupyterLab JavaScript dependencies, then distributes the resulting bundle in, for example, a Python pip or conda package. Installing a prebuilt extensions does not require Node.js.
  33. An extension can be published both as a source extension on NPM and as a prebuilt extension (e.g., published as a Python package). In some cases, system administrators may even choose to install a prebuilt extension by directly copying the prebuilt bundle to an appropriate directory, circumventing the need to create a Python package. If a source extension and a prebuilt extension with the same name are installed in JupyterLab, the prebuilt extension takes precedence.
  34. Because prebuilt extensions do not require a JupyterLab rebuild, they have a distinct advantage in multiuser systems where JuptyerLab is installed at the system level. On such systems, only the system administrator has permissions to rebuild JupyterLab and install source extensions. Since prebuilt extensions can be installed at the per-user level, the per-environment level, or the system level, each user can have their own separate set of prebuilt extensions that are loaded dynamically in their browser on top of the system-wide JupyterLab.
  35. .. tip::
  36. We recommend publishing prebuilt extensions in Python packages for user convenience.
  37. Plugins
  38. -------
  39. A JupyterLab plugin is the basic unit of extensibility in JupyterLab. JupyterLab supports several types of plugins:
  40. - **Application plugins:** Application plugins are the fundamental building block of JupyterLab functionality. Application plugins interact with JupyterLab and other plugins by requiring services provided by other plugins, and optionally providing their own service to the system.
  41. - **Mime renderer plugins:** Mime renderer plugins are simplified, restricted ways to extend JupyterLab to render custom mime data in notebooks and files. These plugins are automatically converted to equivalent application plugins by JupyterLab when they are loaded.
  42. - **Theme plugins:** Theme plugins provide a way to customize the appearance of JupyterLab by changing themeable values (i.e., CSS variable values) and providing additional fonts and graphics to JupyterLab.
  43. Application Plugins
  44. ^^^^^^^^^^^^^^^^^^^
  45. An application plugin is a JavaScript object with a number of metadata fields. The ``id`` and ``activate`` fields are required and the other fields may be omitted. For more information about how to use the ``requires``, ``optional``, or ``provides`` fields, see :ref:`services`.
  46. A typical application plugin might look like this in TypeScript:
  47. .. code-block:: typescript
  48. const plugin: JupyterFrontEndPlugin<MyToken> = {
  49. id: 'my-extension:plugin',
  50. autoStart: true,
  51. requires: [ILabShell, ITranslator],
  52. optional: [ICommandPalette],
  53. provides: MyToken,
  54. activate: activateFunction
  55. };
  56. - ``id`` is a required unique string. The convention is to use the NPM extension package name, a colon, then a string identifying the plugin inside the extension.
  57. - ``autostart`` indicates whether your plugin should be activated at application startup. Typically this should be ``true``. If it is ``false`` or omitted, your plugin will be activated when any other plugin requests the token your plugin is providing.
  58. - ``requires`` and ``optional`` are lists of tokens corresponding to services other plugins provide. These services will be given as arguments to the ``activate`` function when the plugin is activated. If a ``requires`` service is not registered with JupyterLab, an error will be thrown and the plugin will not be activated.
  59. - ``provides`` is the token associated with the service your plugin is providing to the system. If your plugin does not provide a service to the system, omit this field and do not return a value from your ``activate`` function.
  60. - ``activate`` is the function called when your plugin is activated. The arguments are, in order, the :ref:`application_object`, the services corresponding to the ``requires`` tokens, then the services corresponding to the ``optional`` tokens (or ``null`` if that particular ``optional`` token is not registered in the system). If a ``provides`` token is given, the return value of the ``activate`` function (or resolved return value if a promise is returned) will be registered as the service associated with the token.
  61. .. _application_object:
  62. Application Object
  63. """"""""""""""""""
  64. A Jupyter front-end application object is given to each plugin ``activate`` function as its first argument. The application object has a number of properties and methods for interacting with the application, including:
  65. - ``commands`` - an extensible registry used to add and execute commands in the application.
  66. - ``docRegistry`` - an extensible registry containing the document types that the application is able to read and render.
  67. - ``restored`` - a promise that is resolved when the application has finished loading.
  68. - ``serviceManager`` - low-level manager for talking to the Jupyter REST API.
  69. - ``shell`` - a generic Jupyter front-end shell instance, which holds the user interface for the application. See :ref:`shell` for more details.
  70. See the JupyterLab API reference documentation for the ``JupyterFrontEnd`` class for more details.
  71. .. _services:
  72. Plugins Interacting with Each Other
  73. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  74. One of the foundational features of the JupyterLab plugin system is that application plugins can interact with other plugins by providing a service to the system and requiring services provided by other plugins. A service can be any JavaScript value, and typically is a JavaScript object with methods and data attributes. For example, the core plugin that supplies the JupyterLab main menu provides a :ref:`mainmenu` service object to the system with a method to add a new top-level menu and attributes to interact with existing top-level application menus.
  75. In the following discussion, the plugin that is providing a service to the system is the *provider* plugin, and the plugin that is requiring and using the service is the *consumer* plugin.
  76. A service provided by a plugin is identified by a *token*, i.e., a concrete instance of the Lumino Token class. The provider plugin lists the token in its plugin metadata ``provides`` field, and returns the associated service from its ``activate`` function. Consumer plugins import the token (for example, from the provider plugin's extension JavaScript package) and list the token in their plugin metadata ``requires`` or ``optional`` fields. When JupyterLab instantiates the consumer plugin, it will pass in the service associated with the token. JupyterLab orders plugin activation to ensure that a provider of a service is activated before its consumers. A token can only be registered with the system once.
  77. A token defined in TypeScript can also define a TypeScript interface for the service associated with the token. If the provider or consumer uses TypeScript, the service will be type-checked against this interface.
  78. .. note::
  79. JupyterLab uses tokens to identify services (instead of strings, for example) to prevent conflicts between identifiers and to enable type checking when using TypeScript.
  80. Publishing Tokens
  81. """""""""""""""""
  82. Since consumers will need to import a token used by a provider, the token should be exported in a published JavaScript package. A pattern in core JupyterLab is to create and export tokens from a self-contained ``tokens`` JavaScript module in a package. This enables consumers to import a token directly from the package's ``tokens`` module (e.g., ``import { MyToken } from 'provider/tokens';``), thus enabling a tree-shaking bundling optimization to possibly bundle only the tokens and not other code from the package.
  83. Another pattern in core JupyterLab is to create and export a token from a third package that both the provider and consumer extensions import, rather than defining the token in the provider's package. This enables a user to swap out the provider extension for a different extension that provides the same token with an alternative service implementation. For example, the core JupyterLab ``filebrowser`` package exports a token representing the file browser service (enabling interactions with the file browser). The ``filebrowser-extension`` package contains a plugin that implements the file browser in JupyterLab and provides the file browser service to JupyterLab (identified with the token imported from the ``filebrowser`` package). Extensions in JupyterLab that want to interact with the filebrowser thus do not need to have a JavaScript dependency on the ``filebrowser-extension`` package, but only need to import the token from the ``filebrowser`` package. This pattern enables users to seamlessly change the file browser in JupyterLab by writing their own extension that imports the same token from the ``filebrowser`` package and provides it to the system with their own alternative file browser service.
  84. .. _deduplication:
  85. Deduplication of Dependencies
  86. """""""""""""""""""""""""""""
  87. ..
  88. TODO: Maybe put this part in the place where we talk about the sharedPackages metadata? It's an important implementation detail in JupyterLab that has consequences for extension metadata.
  89. One important concern and challenge in the JupyterLab extension system is deduplicating dependencies of extensions instead of having extensions use their own bundled copies of dependencies. For example, the Lumino widgets system on which JupyterLab relies for communication across the application requires all packages use the same copy of the ``@lumino/widgets`` package. Tokens identifying plugin services also need to be shared across the providers and consumers of the services, so dependencies that export tokens need to be deduplicated.
  90. Deduplication in JupyterLab happens in two ways. For source extensions, JupyterLab deduplicates dependencies when rebuilds itself to include the extension during the extension installation process. Deduplication is one of the main reasons JupyterLab needs to be rebuilt when installing source extensions. For prebuilt extensions, JupyterLab relies on the Webpack 5.0 module federation system to share dependencies across different bundles (including the core JupyterLab application bundle).
  91. To ensure that a consumer gets the same token instance that the provider provided to the sytem, the consumer should list the package it imported the tokens from as unbundled package in its ``package.json`` ``jupyterlab.sharedPackages`` config—this will generate a JavaScript error if the package (and thus the token) is not present in the system at runtime. Optional token packages should be listed as singletons that are bundled (otherwise, if they are not present in the system, it will cause a js error when you try to import them).
  92. .. _rendermime:
  93. Mime Renderer Plugins
  94. ^^^^^^^^^^^^^^^^^^^^^
  95. Mime Renderer plugins are a convenience for creating an plugin
  96. that can render mime data and potentially render files of a given type.
  97. We provide an extension cookiecutter for mime renderer plugins in TypeScript
  98. `here <https://github.com/jupyterlab/mimerender-cookiecutter-ts>`__.
  99. Mime renderer plugins are more declarative than standard plugins.
  100. The extension is treated the same from the command line perspective
  101. (``jupyter labextension install`` ), but it does not directly create
  102. JupyterLab plugins. Instead it exports an interface given in the
  103. `rendermime-interfaces <https://jupyterlab.github.io/jupyterlab/interfaces/_rendermime_interfaces_src_index_.irendermime.iextension.html>`__
  104. package.
  105. The JupyterLab repo has an example mime renderer extension for
  106. `pdf <https://github.com/jupyterlab/jupyterlab/tree/master/packages/pdf-extension>`__
  107. files. It provides a mime renderer for pdf data and registers itself as
  108. a document renderer for pdf file types.
  109. The JupyterLab organization also has a mime renderer extension tutorial
  110. which adds mp4 video rendering to the application
  111. `here <https://github.com/jupyterlab/jupyterlab-mp4>`__.
  112. The ``rendermime-interfaces`` package is intended to be the only
  113. JupyterLab package needed to create a mime renderer extension (using the
  114. interfaces in TypeScript or as a form of documentation if using plain
  115. JavaScript).
  116. The only other difference from a standard extension is that it has a
  117. ``jupyterlab`` key in its ``package.json`` with ``"mimeExtension"``
  118. metadata. The value can be ``true`` to use the main module of the
  119. package, or a string path to a specific module (e.g. ``"lib/foo"``).
  120. The mime renderer can update its data by calling ``.setData()`` on the
  121. model it is given to render. This can be used for example to add a
  122. ``png`` representation of a dynamic figure, which will be picked up by a
  123. notebook model and added to the notebook document. When using
  124. ``IDocumentWidgetFactoryOptions``, you can update the document model by
  125. calling ``.setData()`` with updated data for the rendered MIME type. The
  126. document can then be saved by the user in the usual manner.
  127. Theme plugins
  128. ^^^^^^^^^^^^^
  129. A theme is a JupyterLab plugin that uses a ``ThemeManager`` and can
  130. be loaded and unloaded dynamically. The package must include all static
  131. assets that are referenced by ``url()`` in its CSS files. Local URLs can
  132. be used to reference files relative to the location of the referring sibling CSS files. For example ``url('images/foo.png')`` or
  133. ``url('../foo/bar.css')``\ can be used to refer local files in the
  134. theme. Absolute URLs (starting with a ``/``) or external URLs (e.g.
  135. ``https:``) can be used to refer to external assets. The path to the
  136. theme asset entry point is specified ``package.json`` under the ``"jupyterlab"``
  137. key as ``"themePath"``. See the `JupyterLab Light
  138. Theme <https://github.com/jupyterlab/jupyterlab/tree/master/packages/theme-light-extension>`__
  139. for an example. Ensure that the theme files are included in the
  140. ``"files"`` metadata in ``package.json``. Note that if you want to use SCSS, SASS, or LESS files,
  141. you must compile them to CSS and point JupyterLab to the CSS files.
  142. The theme extension is installed in the same way as a regular extension (see
  143. `extension authoring <#extension-authoring>`__).
  144. It is also possible to create a new theme using the
  145. `TypeScript theme cookiecutter <https://github.com/jupyterlab/theme-cookiecutter>`__.
  146. Source Extensions
  147. -----------------
  148. A source extension is a JavaScript package that exports one or more plugins.
  149. package.json metadata
  150. ^^^^^^^^^^^^^^^^^^^^^
  151. A source extension has metadata in the ``jupyterlab`` field of its ``package.json`` file. The JSON schema for the metadata is `distributed <https://github.com/jupyterlab/jupyterlab/blob/master/builder/metadata_schema.json>`__ in the ``@jupyterlab/builder`` package.
  152. We recommend including the keyword ``jupyterlab-extension`` in ``package.json`` to enable the extension manager to search for the extension in the npm repository::
  153. "keywords": [
  154. "jupyterlab-extension"
  155. ],
  156. Main entry point
  157. """"""""""""""""
  158. The ``jupyterlab.extension`` field signifies that this package is a JupyterLab extension and gives the module that exports a plugin or list of plugins as default exports. Set the value to ``true`` if plugins are the default exports from the main package module (i.e., the file listed in the ``main`` key of ``package.json``). If your plugins are exported by a different module, set this to the relative path to the module (e.g., ``"lib/foo"``). Example::
  159. "jupyterlab": {
  160. "extension": true
  161. }
  162. Plugin Settings
  163. """""""""""""""
  164. JupyterLab exposes a plugin settings system that can be used to provide
  165. default setting values and user overrides. This uses the ``jupyterlab.schemaDir`` field of the extension metadata.
  166. An extension can specify user settings using a JSON Schema. The schema
  167. definition should be in a file that resides in the ``schemaDir``
  168. directory that is specified in the ``package.json`` file of the
  169. extension. The actual file name should use is the part that follows the
  170. package name of extension. So for example, the JupyterLab
  171. ``apputils-extension`` package hosts several plugins:
  172. - ``'@jupyterlab/apputils-extension:menu'``
  173. - ``'@jupyterlab/apputils-extension:palette'``
  174. - ``'@jupyterlab/apputils-extension:settings'``
  175. - ``'@jupyterlab/apputils-extension:themes'``
  176. And in the ``package.json`` for ``@jupyterlab/apputils-extension``, the
  177. ``schemaDir`` field is a directory called ``schema``. Since the
  178. ``themes`` plugin requires a JSON schema, its schema file location is:
  179. ``schema/themes.json``. The plugin's name is used to automatically
  180. associate it with its settings file, so this naming convention is
  181. important. Ensure that the schema files are included in the ``"files"``
  182. metadata in ``package.json``.
  183. See the
  184. `fileeditor-extension <https://github.com/jupyterlab/jupyterlab/tree/master/packages/fileeditor-extension>`__
  185. for another example of an extension that uses settings.
  186. A system administrator or user can override default values of extension settings with the :ref:`overrides.json <overridesjson>` file.
  187. Disabling other extensions
  188. """"""""""""""""""""""""""
  189. The ``disabledExtensions`` field gives a list of extensions or regex patterns for extensions or plugins to disable when this extension is installed, with the same semantics as the ``disabledExtensions`` field of :ref:`page_config.json <page_configjson>`. This can be used to automatically override and disable built-in extensions. For example, if an extension replaces the plugins provided by the core status bar extension, you can disable the core status bar extension automatically with::
  190. "jupyterlab": {
  191. "disabledExtensions": ["@jupyterlab/statusbar-extension"]
  192. }
  193. Sharing configuration
  194. """""""""""""""""""""
  195. By default, an extension's dependencies will be shared and deduplicated with other extension's direct dependencies, and JupyterLab will bundle a copy of the dependency. The ``sharedPackages`` key enables you to control how dependencies are bundled with your extension when building JupyterLab (or when building your extension when creating a prebuilt extension). ``sharedPackages`` is an object where the keys are JavaScript package names and values are sharing configuration. Set the value to ``false`` to not share a dependency with other packages. Set the value to an object to control how it is shared.
  196. Usually the only fields needed here are ``bundled: false`` to not bundle a dependency (but rely on another extension to bundle the dependency). Do this if you import a token from the dependency,
  197. .. _ext-author-companion-packages:
  198. Companion packages
  199. """"""""""""""""""
  200. If your extension depends on the presence of one or more packages in the
  201. kernel, or on a notebook server extension, you can add metadata to indicate
  202. this to the extension manager by adding metadata to your package.json file.
  203. The full options available are::
  204. "jupyterlab": {
  205. "discovery": {
  206. "kernel": [
  207. {
  208. "kernel_spec": {
  209. "language": "<regexp for matching kernel language>",
  210. "display_name": "<regexp for matching kernel display name>" // optional
  211. },
  212. "base": {
  213. "name": "<the name of the kernel package>"
  214. },
  215. "overrides": { // optional
  216. "<manager name, e.g. 'pip'>": {
  217. "name": "<name of kernel package on pip, if it differs from base name>"
  218. }
  219. },
  220. "managers": [ // list of package managers that have your kernel package
  221. "pip",
  222. "conda"
  223. ]
  224. }
  225. ],
  226. "server": {
  227. "base": {
  228. "name": "<the name of the server extension package>"
  229. },
  230. "overrides": { // optional
  231. "<manager name, e.g. 'pip'>": {
  232. "name": "<name of server extension package on pip, if it differs from base name>"
  233. }
  234. },
  235. "managers": [ // list of package managers that have your server extension package
  236. "pip",
  237. "conda"
  238. ]
  239. }
  240. }
  241. }
  242. A typical setup for e.g. a jupyter-widget based package will then be::
  243. "keywords": [
  244. "jupyterlab-extension",
  245. "jupyter",
  246. "widgets",
  247. "jupyterlab"
  248. ],
  249. "jupyterlab": {
  250. "extension": true,
  251. "discovery": {
  252. "kernel": [
  253. {
  254. "kernel_spec": {
  255. "language": "^python",
  256. },
  257. "base": {
  258. "name": "myipywidgetspackage"
  259. },
  260. "managers": [
  261. "pip",
  262. "conda"
  263. ]
  264. }
  265. ]
  266. }
  267. }
  268. Currently supported package managers are ``pip`` and ``conda``.
  269. Custom webpack config
  270. """""""""""""""""""""
  271. .. warning::
  272. This feature is *experimental*, as it makes it possible to override the base config used by the
  273. JupyterLab Federated Extension System.
  274. It also exposes the internals of the federated extension build system (namely ``webpack``) to extension authors, which was until now
  275. kept as an implementation detail.
  276. The JupyterLab Federated Extension System uses ``webpack`` to build federated extensions, relying on the
  277. `Module Federation System <https://webpack.js.org/concepts/module-federation/>`_ added in webpack 5.
  278. To specify a custom webpack config to the federated extension build system, extension authors can add the ``webpackConfig`` subkey to the
  279. ``package.json`` of their extension::
  280. "jupyterlab": {
  281. "webpackConfig": "webpack.config.js"
  282. }
  283. The webpack config file can be placed in a different location with a custom name::
  284. "jupyterlab": {
  285. "webpackConfig": "./config/test-config.js"
  286. }
  287. Here is an example of a custom config that enables the async WebAssembly and top-level ``await`` experiments:
  288. .. code-block:: javascript
  289. module.exports = {
  290. experiments: {
  291. topLevelAwait: true,
  292. asyncWebAssembly: true,
  293. }
  294. };
  295. This custom config will be merged with the `default config <https://github.com/jupyterlab/jupyterlab/blob/master/builder/src/webpack.config.base.ts>`_
  296. when building the federated extension with ``jlpm run build``.
  297. Packaging extensions
  298. ^^^^^^^^^^^^^^^^^^^^
  299. Most extensions are single JavaScript packages, and can be shipped on npmjs.org.
  300. This makes them discoverable by the JupyterLab extension manager, provided they
  301. have the ``jupyterlab-extension`` keyword in their ``package.json``. If the package also
  302. contains a server extension (Python package), the author has two options.
  303. The server extension and the JupyterLab extension can be shipped in a single package,
  304. or they can be shipped separately.
  305. The JupyterLab extension can be bundled in a package on PyPI and conda-forge so
  306. that it ends up in the user's application directory. Note that the user will still have to run ``jupyter lab build``
  307. (or build when prompted in the UI) in order to use the extension.
  308. The general idea is to pack the Jupyterlab extension using ``npm pack``, and then
  309. use the ``data_files`` logic in ``setup.py`` to ensure the file ends up in the
  310. ``<jupyterlab_application>/share/jupyter/lab/extensions``
  311. directory.
  312. Note that even if the JupyterLab extension is unusable without the
  313. server extension, as long as you use the companion package metadata it is still
  314. useful to publish it to npmjs.org so it is discoverable by the JupyterLab extension manager.
  315. The server extension can be enabled on install by using ``data_files``.
  316. an example of this approach is `jupyterlab-matplotlib <https://github.com/matplotlib/jupyter-matplotlib/tree/ce9cc91e52065d33e57c3265282640f2aa44e08f>`__. The file used to enable the server extension is `here <https://github.com/matplotlib/jupyter-matplotlib/blob/ce9cc91e52065d33e57c3265282640f2aa44e08f/jupyter-matplotlib.json>`__. The logic to ship the JS tarball and server extension
  317. enabler is in `setup.py <https://github.com/matplotlib/jupyter-matplotlib/blob/ce9cc91e52065d33e57c3265282640f2aa44e08f/setup.py>`__. Note that the ``setup.py``
  318. file has additional logic to automatically create the JS tarball as part of the
  319. release process, but this could also be done manually.
  320. Prebuilt Extensions
  321. -------------------
  322. package.json metadata
  323. ^^^^^^^^^^^^^^^^^^^^^
  324. In addition to the package metadata given above, prebuilt extensions have extra metadata for where the prebuilt assets should go.
  325. Packaging Information
  326. ^^^^^^^^^^^^^^^^^^^^^
  327. Since prebuilt extensions are distributed in many ways, there is an extra file, ``install.json`` that helps the user know how a prebuilt extension was installed. This file is put there by the packaging system distributing the prebuilt extension.
  328. How prebuilt extensions work
  329. """""""""""""""""""""""""""""
  330. Steps for building
  331. """"""""""""""""""
  332. - We provide a ``jupyter labextension build`` script that is used to build prebuilt bundles
  333. - The command produces a set of static assets that are shipped along with a package (notionally on ``pip``/``conda``)
  334. - It is a Python cli so that it can use the dependency metadata from the active JupyterLab
  335. - The assets include a module federation ``remoteEntry.*.js``, generated bundles, and some other files that we use
  336. - ``package.json`` is the original ``package.json`` file that we use to gather metadata about the package, with some included build metadata
  337. - we use the previously existing ``@jupyterlab/builder -> build`` to generate the ``imports.css``, ``schemas`` and ``themes`` file structure
  338. - We provide a ``labextensions`` handler in ``jupyterlab_server`` that loads static assets from ``labextensions`` paths, following a similar logic to how ``nbextensions`` are discovered and loaded from disk
  339. - The ``settings`` and ``themes`` handlers in ``jupyterlab_server`` has been updated to load from the new ``labextensions`` locations, favoring the prebuilt extension locations over the bundled ones
  340. - A ``labextension develop`` command has been added to install an in-development extension into JupyterLab. The default behavior is to create a symlink in the ``sys-prefix/share/jupyter/labextensions/package-name`` to the static directory of the extension
  341. - We provide a ``cookiecutter`` that handles all of the scaffolding for an extension author, including the shipping of ``data_files`` so that when the user installs the package, the static assets end up in ``share/jupyter/labextensions``
  342. Directory walkthrough
  343. """""""""""""""""""""
  344. Runtime configuration
  345. ---------------------
  346. - We handle disabling of lab extensions using a trait on the ``LabApp`` class, so it can be set by admins and overridden by users. Extensions are automatically enabled when installed, and must be explicitly disabled. The disabled config can consist of a package name or a plugin regex pattern
  347. - ``page_config`` and ``overrides`` are also handled with traits so that admins can provide defaults and users can provide overrides
  348. Development workflow
  349. --------------------
  350. We encourage extension authors to add the `jupyterlab-extension GitHub topic
  351. <https://github.com/search?utf8=%E2%9C%93&q=topic%3Ajupyterlab-extension&type=Repositories>`__ to any GitHub extension repository.
  352. While authoring the extension, you can use the command:
  353. .. code-block:: bash
  354. npm install # install npm package dependencies
  355. npm run build # optional build step if using TypeScript, babel, etc.
  356. jupyter labextension install # install the current directory as an extension
  357. This causes the builder to re-install the source folder before building
  358. the application files. You can re-build at any time using
  359. ``jupyter lab build`` and it will reinstall these packages.
  360. You can also link other local ``npm`` packages that you are working on
  361. simultaneously using ``jupyter labextension link``; they will be re-installed
  362. but not considered as extensions. Local extensions and linked packages are
  363. included in ``jupyter labextension list``.
  364. When using local extensions and linked packages, you can run the command
  365. ::
  366. jupyter lab --watch
  367. This will cause the application to incrementally rebuild when one of the
  368. linked packages changes. Note that only compiled JavaScript files (and
  369. the CSS files) are watched by the WebPack process. This means that if
  370. your extension is in TypeScript you'll have to run a ``jlpm run build``
  371. before the changes will be reflected in JupyterLab. To avoid this step
  372. you can also watch the TypeScript sources in your extension which is
  373. usually assigned to the ``tsc -w`` shortcut. If WebPack doesn't seem to
  374. detect the changes, this can be related to `the number of available watches <https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers>`__.
  375. Note that the application is built against **released** versions of the
  376. core JupyterLab extensions. If your extension depends on JupyterLab
  377. packages, it should be compatible with the dependencies in the
  378. ``jupyterlab/static/package.json`` file. Note that building will always use the latest JavaScript packages that meet the dependency requirements of JupyterLab itself and any installed extensions. If you wish to test against a
  379. specific patch release of one of the core JupyterLab packages you can
  380. temporarily pin that requirement to a specific version in your own
  381. dependencies.
  382. If you must install an extension into a development branch of JupyterLab, you have to graft it into the source tree of JupyterLab itself. This may be done using the command
  383. ::
  384. jlpm run add:sibling <path-or-url>
  385. in the JupyterLab root directory, where ``<path-or-url>`` refers either
  386. to an extension ``npm`` package on the local file system, or a URL to a git
  387. repository for an extension ``npm`` package. This operation may be
  388. subsequently reversed by running
  389. ::
  390. jlpm run remove:package <extension-dir-name>
  391. This will remove the package metadata from the source tree and delete
  392. all of the package files.
  393. The package should export EMCAScript 6 compatible JavaScript. It can
  394. import CSS using the syntax ``require('foo.css')``. The CSS files can
  395. also import CSS from other packages using the syntax
  396. ``@import url('~foo/index.css')``, where ``foo`` is the name of the
  397. package.
  398. The following file types are also supported (both in JavaScript and
  399. CSS): ``json``, ``html``, ``jpg``, ``png``, ``gif``, ``svg``,
  400. ``js.map``, ``woff2``, ``ttf``, ``eot``.
  401. If your package uses any other file type it must be converted to one of
  402. the above types or `include a loader in the import statement <https://webpack.js.org/concepts/loaders/#inline>`__.
  403. If you include a loader, the loader must be importable at build time, so if
  404. it is not already installed by JupyterLab, you must add it as a dependency
  405. of your extension.
  406. If your JavaScript is written in any other dialect than
  407. EMCAScript 6 (2015) it should be converted using an appropriate tool.
  408. You can use Webpack to pre-build your extension to use any of it's features
  409. not enabled in our build configuration. To build a compatible package set
  410. ``output.libraryTarget`` to ``"commonjs2"`` in your Webpack configuration.
  411. (see `this <https://github.com/saulshanabrook/jupyterlab-webpack>`__ example repo).
  412. Another option to try out your extension with a local version of JupyterLab is to add it to the
  413. list of locally installed packages and to have JupyterLab register your extension when it starts up.
  414. You can do this by adding your extension to the ``jupyterlab.externalExtensions`` key
  415. in the ``dev_mode/package.json`` file. It should be a mapping
  416. of extension name to version, just like in ``dependencies``. Then run ``jlpm run integrity``
  417. and these extensions should be added automatically to the ``dependencies`` and pulled in.
  418. When you then run ``jlpm run build && jupyter lab --dev`` or ``jupyter lab --dev --watch`` this extension
  419. will be loaded by default. For example, this is how you can add the Jupyter Widgets
  420. extensions:
  421. ::
  422. "externalExtensions": {
  423. "@jupyter-widgets/jupyterlab-manager": "2.0.0"
  424. },
  425. If you publish your extension on ``npm.org``, users will be able to install
  426. it as simply ``jupyter labextension install <foo>``, where ``<foo>`` is
  427. the name of the published ``npm`` package. You can alternatively provide a
  428. script that runs ``jupyter labextension install`` against a local folder
  429. path on the user's machine or a provided tarball. Any valid
  430. ``npm install`` specifier can be used in
  431. ``jupyter labextension install`` (e.g. ``foo@latest``, ``bar@3.0.0.0``,
  432. ``path/to/folder``, and ``path/to/tar.gz``).
  433. Testing your extension
  434. ^^^^^^^^^^^^^^^^^^^^^^
  435. There are a number of helper functions in ``testutils`` in this repo (which
  436. is a public ``npm`` package called ``@jupyterlab/testutils``) that can be used when
  437. writing tests for an extension. See ``tests/test-application`` for an example
  438. of the infrastructure needed to run tests. There is a ``karma`` config file
  439. that points to the parent directory's ``karma`` config, and a test runner,
  440. ``run-test.py`` that starts a Jupyter server.
  441. If you are using `jest <https://jestjs.io/>`__ to test your extension, you will
  442. need to transpile the jupyterlab packages to ``commonjs`` as they are using ES6 modules
  443. that ``node`` does not support.
  444. To transpile jupyterlab packages, you need to install the following package:
  445. ::
  446. jlpm add --dev jest@^24 @types/jest@^24 ts-jest@^24 @babel/core@^7 @babel/preset-env@^7
  447. Then in `jest.config.js`, you will specify to use babel for js files and ignore
  448. all node modules except the jupyterlab ones:
  449. ::
  450. module.exports = {
  451. preset: 'ts-jest/presets/js-with-babel',
  452. moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  453. transformIgnorePatterns: ['/node_modules/(?!(@jupyterlab/.*)/)'],
  454. globals: {
  455. 'ts-jest': {
  456. tsConfig: 'tsconfig.json'
  457. }
  458. },
  459. ... // Other options useful for your extension
  460. };
  461. Finally, you will need to configure babel with a ``babel.config.js`` file containing:
  462. ::
  463. module.exports = {
  464. presets: [
  465. [
  466. '@babel/preset-env',
  467. {
  468. targets: {
  469. node: 'current'
  470. }
  471. }
  472. ]
  473. ]
  474. };