1
0
mirror of https://github.com/mpv-player/mpv synced 2024-12-26 00:42:57 +00:00

js: require: allow custom module search paths via mp.module_paths

This commit is contained in:
Avi Halachmi (:avih) 2019-12-14 19:34:58 +02:00
parent 3d2e30d764
commit 4fc5cd32d0
2 changed files with 18 additions and 4 deletions

View File

@ -240,6 +240,9 @@ Note: ``read_file`` and ``write_file`` throw on errors, allow text content only.
anything from the filesystem), and returns it as a function. Very similar
to a ``Function`` constructor, but shows at stack traces as ``fname``.
``mp.module_paths``
Global modules search paths array for the ``require`` function (see below).
Timers (global)
---------------
@ -301,6 +304,11 @@ or ``~/x``. Otherwise, it's considered a global module id and searched at
``require("x")`` is searched as file ``x.js`` at those dirs, and id ``foo/x`` is
searched as file ``x.js`` inside dir ``foo`` at those dirs.
Search paths for global module id's are at the array ``mp.module_paths``, which
is searched in order. Initially it contains one item: ``~~/scripts/modules.js``
such that it behaves as described above. Modifying it will affect future
``require`` calls with global module id's which are not already loaded/cached.
No ``global`` variable, but a module's ``this`` at its top lexical scope is the
global object - also in strict mode. If you have a module which needs ``global``
as the global object, you could do ``this.global = this;`` before ``require``.

View File

@ -375,6 +375,8 @@ function process_timers() {
- Module id supports mpv path enhancements, e.g. ~/foo, ~~/bar, ~~desktop/baz
*********************************************************************/
mp.module_paths = ["~~/scripts/modules.js"]; // global modules search paths
// Internal meta top-dirs. Users should not rely on these names.
var MODULES_META = "~~modules",
SCRIPTDIR_META = "~~scriptdir", // relative script path -> meta absolute id
@ -389,10 +391,14 @@ function resolve_module_file(id) {
return mp.utils.join_path(main_script[0], rest);
if (base == MODULES_META) {
var path = mp.find_config_file("scripts/modules.js/" + rest);
if (!path)
throw(Error("Cannot find module file '" + rest + "'"));
return path;
for (var i = 0; i < mp.module_paths.length; i++) {
try {
var f = mp.utils.join_path(mp.module_paths[i], rest);
mp.utils.read_file(f, 1); // throws on any error
return f;
} catch (e) {}
}
throw(Error("Cannot find module file '" + rest + "'"));
}
return id + ".js";