[英]How to set a including path in the Gjs code?
如我所見,Gjs imports
,默認情況下僅加載/usr/share/gjs-1.0
和/usr/lib/gjs-1.0
。 我想模塊化一個應用程序,就像我們可以用節點做的那樣,但我必須找到與腳本文件相關的模塊。
我發現這兩種添加包含路徑的方法:
gjs --include-path=my-modules my-script.js
GJS_PATH=my-modules gjs my-script.js
...但是兩者都與當前目錄相關,而不是與文件相關(很明顯) ,並且它們需要在命令行上聲明,從而使這變得不必要的復雜。
如何在 Gjs 代碼中設置包含路徑? (所以我可以使它相對於文件)
或者...還有另一種方法可以從任何地方導入文件,比如 python?
(拜托,你不需要提議使用 shellscript 啟動器來解決 --include --include-path
和GJS_PATH
問題。這很明顯,但功能較弱。如果我們沒有更好的解決方案,我們就可以生存。)
您需要設置或修改imports.searchPath
(這並不明顯,因為它沒有出現for (x in imports)print(x)
)。 所以這:
imports.searchPath.unshift('.');
var foo = imports.foo;
將文件“foo.js”導入為foo
object。
這與Seed兼容,盡管imports
知道它有一個searchPath
。
(這個答案的早期版本不太准確,而且更具煽動性。抱歉)。
正如道格拉斯所說,您確實需要修改imports.searchPath
以包含您的圖書館位置。 使用.
很簡單,但取決於始終從同一目錄位置運行的文件。 不幸的是,找到當前正在執行的腳本的目錄是一個巨大的難題。 以下是Gnome Shell 對擴展 API 的處理方式
我已將其改編為以下 function 以供一般使用:
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()];
}
在定義getCurrentFile
function 之后,您可以通過入口點文件app.js
使用它:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.