expose require() instead of the svelte global

- Means add-on authors should not need to inject any code in their build
- Should be more flexible - we can export multiple libraries if we wish,
and don't have to worry about require() being clobbered by old add-ons.
This commit is contained in:
Damien Elmes 2021-08-24 10:19:26 +10:00
parent fdf8321253
commit 12ea482c87
6 changed files with 33 additions and 8 deletions

View File

@ -5,7 +5,7 @@
@typescript-eslint/no-explicit-any: "off",
*/
import "sveltelib/export-internal";
import "sveltelib/export-runtime";
import { getDeckOptionsInfo, DeckOptionsState } from "./lib";
import { setupI18n, ModuleName } from "lib/i18n";

View File

@ -6,7 +6,7 @@
@typescript-eslint/no-explicit-any: "off",
*/
import "sveltelib/export-internal";
import "sveltelib/export-runtime";
import { filterHTML } from "html-filter";
import { updateActiveButtons } from "./toolbar";

19
ts/lib/runtime-require.ts Normal file
View File

@ -0,0 +1,19 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/* eslint
@typescript-eslint/no-explicit-any: "off",
*/
/// This can be extended to allow require() calls at runtime, for libraries
/// that are not included at bundling time.
export const runtimeLibraries = {};
// Export require() as a global.
(globalThis as any).require = function (name: string): unknown {
const lib = runtimeLibraries[name];
if (lib === undefined) {
throw new Error(`Cannot require(${name}) at runtime.`);
}
return lib;
};

View File

@ -13,6 +13,7 @@ ts_library(
tsconfig = "//:tsconfig.json",
visibility = ["//visibility:public"],
deps = [
"//ts/lib",
"@npm//svelte",
"@npm//tslib",
],

View File

@ -1,6 +0,0 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
// allow Svelte add-ons
import * as svelte_internal from "svelte/internal";
window["svelte_internal"] = svelte_internal;

View File

@ -0,0 +1,11 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
//
// Expose the Svelte runtime bundled with Anki, so that add-ons can require() it.
// If they were to bundle their own runtime, things like bindings and contexts
// would not work.
import { runtimeLibraries } from "lib/runtime-require";
import * as svelteRuntime from "svelte/internal";
runtimeLibraries["svelte/internal"] = svelteRuntime;