正如我所看到的,Gjs imports默认只加载/usr/share/gjs-1.0和/usr/lib/gjs-1.0。我想模块化一个应用程序,就像我们可以使用节点一样,但是我必须找到相对于脚本文件的模块。
我发现了添加包含路径的两种方法:
gjs --include-path=my-modules my-script.jsGJS_PATH=my-modules gjs my-script.js...but与当前目录无关,而与文件无关,需要在命令行中声明它们,这使得这变得不必要地复杂。
如何在Gjs代码中设置包含路径?(这样我就可以使这个相对于文件)
或者..。还有另一种从任何地方导入文件的方法,比如python?
(请不要建议使用solve脚本启动程序来解决--include-path和GJS_PATH问题。这是显而易见的,但没有那么强大。如果我们没有一个更好的解决方案,我们就能生存下去。)
发布于 2012-05-29 11:25:20
您需要设置或修改imports.searchPath (这并不明显,因为它没有在for (x in imports)print(x)中显示)。所以这个:
imports.searchPath.unshift('.');
var foo = imports.foo;将文件“foo.js”导入为foo对象。
这与种子兼容,尽管imports知道它有一个searchPath。
(这个答案的早期版本的准确性要低得多,而且更具煽动性。对不起)。
发布于 2012-12-29 03:02:53
正如道格拉斯所说,您确实需要修改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()];
}下面是如何在定义了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);小毛!现在导入我们的库非常容易:
// import your app libraries (if they were in lib/app_name)
const Core = imports.app_name.core;https://stackoverflow.com/questions/10093102
复制相似问题