From 0e290e18e16c3abdd28608dea7035dc6a1a8b82c Mon Sep 17 00:00:00 2001
From: Tim Paine <3105306+timkpaine@users.noreply.github.com>
Date: Tue, 31 Oct 2023 13:25:40 -0400
Subject: [PATCH] Support es modules in js includes (#2063)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
---
nbconvert/exporters/html.py | 6 +++---
tests/exporters/files/esmodule.html.j2 | 4 ++++
tests/exporters/files/esmodule.js | 2 ++
tests/exporters/test_templateexporter.py | 9 +++++++++
4 files changed, 18 insertions(+), 3 deletions(-)
create mode 100644 tests/exporters/files/esmodule.html.j2
create mode 100644 tests/exporters/files/esmodule.js
diff --git a/nbconvert/exporters/html.py b/nbconvert/exporters/html.py
index 97501ffe3..c2d14be4d 100644
--- a/nbconvert/exporters/html.py
+++ b/nbconvert/exporters/html.py
@@ -304,10 +304,10 @@ def resources_include_lab_theme(name):
code = """""" % data
return markupsafe.Markup(code)
- def resources_include_js(name):
- """Get the resources include JS for a name."""
+ def resources_include_js(name, module=False):
+ """Get the resources include JS for a name. If module=True, import as ES module"""
env = self.environment
- code = """""" % (env.loader.get_source(env, name)[0])
+ code = f""""""
return markupsafe.Markup(code)
def resources_include_url(name):
diff --git a/tests/exporters/files/esmodule.html.j2 b/tests/exporters/files/esmodule.html.j2
new file mode 100644
index 000000000..b71ce7992
--- /dev/null
+++ b/tests/exporters/files/esmodule.html.j2
@@ -0,0 +1,4 @@
+{%- extends 'lab/index.html.j2' -%}
+{%- block html_head_js -%}
+{{ resources.include_js("esmodule.js", True) }}
+{%- endblock html_head_js -%}
diff --git a/tests/exporters/files/esmodule.js b/tests/exporters/files/esmodule.js
new file mode 100644
index 000000000..949bba22e
--- /dev/null
+++ b/tests/exporters/files/esmodule.js
@@ -0,0 +1,2 @@
+const blerg = true
+export { blerg };
diff --git a/tests/exporters/test_templateexporter.py b/tests/exporters/test_templateexporter.py
index 06891afe8..593cfc70a 100644
--- a/tests/exporters/test_templateexporter.py
+++ b/tests/exporters/test_templateexporter.py
@@ -307,6 +307,15 @@ def test_local_template_file_extending_lab(self):
output, resources = exporter.from_notebook_node(nb)
assert "UNIQUE" in output
+ def test_local_template_file_esmodule_js(self):
+ template_file = os.path.join(self._get_files_path(), "esmodule.html.j2")
+ exporter = HTMLExporter(template_file=template_file, template_name="lab")
+ nb = v4.new_notebook()
+ nb.cells.append(v4.new_code_cell("some_text"))
+ output, resources = exporter.from_notebook_node(nb)
+ print(output[:1000])
+ assert '