如何在Gjs代码中设置包含路径?

Aur*_*ium 7 javascript import gnome path gjs

因为我可以看到,GJS imports,只加载/usr/share/gjs-1.0/usr/lib/gjs-1.0默认.我想模块化一个应用程序,就像我们可以用节点做的那样,但我必须找到相对于脚本文件的模块.

我找到了两种添加包含路径的方法:

  1. gjs --include-path=my-modules my-script.js
  2. GJS_PATH=my-modules gjs my-script.js

...但两者都与当前目录相关,而不是文件(不经意地),并且需要在命令行上声明它们,这使得这不必要地复杂.

如何在Gjs代码中设置包含路径?(所以我可以使这个相对于文件)

或者......还有另一种从任何地方导入文件的方法,比如在python中?

(请,你不需要提出使用shell脚本启动解决--include-pathGJS_PATH问题,这是显而易见的,但不那么强大.如果我们没有更好的解决办法,我们与生存.)

Dou*_*all 11

您需要设置或修改imports.searchPath(这不明显,因为它没有显示for (x in imports)print(x)).所以这:

imports.searchPath.unshift('.');
var foo = imports.foo;
Run Code Online (Sandbox Code Playgroud)

导入文件"foo.js"作为foo对象.

这与Seed兼容,虽然imports知道它有一个searchPath.

(这个答案的早期版本实际上不太准确,更具煽动性.抱歉).


Jus*_*ake 7

正如道格拉斯所说,您需要修改imports.searchPath以包含您的图书馆位置.使用.很简单,但取决于始终从同一目录位置运行的文件.不幸的是,找到当前正在执行的脚本的目录是一个巨大的黑客.以下是Gnome Shell如何为扩展API执行此操作

我已将其改编为以下功能以供一般使用:

const Gio = imports.gi.Gio;

function getCurrentFile() {
    let stack = (new Error()).stack;

    // Assuming we're importing this directly from an extension (and we shouldn't
    // ever not be), its UUID should be directly in the path here.
    let stackLine = stack.split('\n')[1];
    if (!stackLine)
        throw new Error('Could not find current file');

    // The stack line is like:
    //   init([object Object])@/home/user/data/gnome-shell/extensions/u@u.id/prefs.js:8
    //
    // In the case that we're importing from
    // module scope, the first field is blank:
    //   @/home/user/data/gnome-shell/extensions/u@u.id/prefs.js:8
    let match = new RegExp('@(.+):\\d+').exec(stackLine);
    if (!match)
        throw new Error('Could not find current file');

    let path = match[1];
    let file = Gio.File.new_for_path(path);
    return [file.get_path(), file.get_parent().get_path(), file.get_basename()];
}
Run Code Online (Sandbox Code Playgroud)

app.js定义getCurrentFile函数后,您可以从入口点文件中使用它:

let file_info = getCurrentFile();

// define library location relative to entry point file
const LIB_PATH = file_info[1] + '/lib';
// then add it to the imports search path
imports.searchPath.unshift(LIB_PATH);
Run Code Online (Sandbox Code Playgroud)

凌晨!现在导入我们的库是非常容易的:

// import your app libraries (if they were in lib/app_name)
const Core = imports.app_name.core;
Run Code Online (Sandbox Code Playgroud)