extension_dev.rst 35 KB

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