8

ご覧のとおり、 Gjsはデフォルトimportsでのみロード/usr/share/gjs-1.0/usr/lib/gjs-1.0れます。ノードでできるように、アプリケーションをモジュール化したいのですが、スクリプト ファイルに関連するモジュールを見つける必要があります。

インクルード パスを追加するには、次の 2 つの方法を見つけました。

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

...しかし、どちらもファイルではなく現在のディレクトリに関連しており(明らかに)、コマンドラインで宣言する必要があり、これが不必要に複雑になっています。

Gjs コードでインクルード パスを設定するにはどうすればよいですか? (だから私はこれをファイルに相対的にすることができます)

または... Pythonのように、どこからでもファイルをインポートする別の方法はありますか?

--include-path(この問題を解決するためにシェルスクリプト ランチャーを使用することを提案する必要はありませんGJS_PATH。それは明らかですが、それほど強力ではありません。より良い解決策がない場合は、それで乗り切ることができます。)

4

2 に答える 2

12

設定または変更する必要がありますimports.searchPath(これは で表示されないためわかりませんfor (x in imports)print(x))。したがって、この:

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

ファイル「foo.js」をfooオブジェクトとしてインポートします。

これはSeedと互換性がありimportsますが、searchPath.

(この回答の以前のバージョンは、正確性が大幅に低下し、より刺激的でした。申し訳ありません)。

于 2012-05-29T11:25:20.923 に答える
10

imports.searchPathDouglas が言うように、ライブラリの場所を含めるように変更する必要があります。使い方.は簡単ですが、常に同じディレクトリの場所から実行されるファイルに依存します。残念ながら、現在実行中のスクリプトのディレクトリを見つけるのは非常に困難です。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;
于 2012-12-29T03:02:53.253 に答える