2012-04-10 58 views
6

正如我所看到的,Gjs imports,默认只加载/usr/share/gjs-1.0/usr/lib/gjs-1.0。我想模块化一个应用程序,就像我们可以使用node一样,但是我必须找到相对于脚本文件的模块。如何在Gjs代码中设置包含路径?

我发现这两种方式来添加包含路径:

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

...但两者都(与当前目录,而不是文件东北角),他们需要在命令行中声明,这使得这不必要的复杂。

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

或...还有另一种方式从任何地方,如在Python中导入文件?

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

回答

8

您需要设置或修改imports.searchPath(这并不明显,因为它没有出现在for (x in imports)print(x)中)。所以这个:

imports.searchPath.unshift('.'); 
var foo = imports.foo; 

导入文件“foo.js”作为foo对象。

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

(此答案的早期版本基本不准确,更具有煽动性,对不起)。

5

正如道格拉斯所说,您确实需要修改imports.searchPath以包含您的图书馆位置。使用.很简单,但取决于始终从同一目录位置运行的文件。不幸的是,找到当前正在执行的脚本的目录是一个巨大的破解。以下是如何Gnome Shell does it for the extensions 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/[email protected]/prefs.js:8 
    // 
    // In the case that we're importing from 
    // module scope, the first field is blank: 
    // @/home/user/data/gnome-shell/extensions/[email protected]/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); 

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

// import your app libraries (if they were in lib/app_name) 
const Core = imports.app_name.core; 
相关问题