【问题标题】:How to set a including path in the Gjs code?如何在 Gjs 代码中设置包含路径?
【发布时间】:2012-04-23 00:00:28
【问题描述】:

如我所见,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 中?

(拜托,你不需要建议使用 shellscript 启动器来解决--include-pathGJS_PATH 的问题。这很明显,但功能较弱。如果我们没有更好的解决方案,我们靠它生存。)

【问题讨论】:

    标签: javascript path gnome import gjs


    【解决方案1】:

    您需要设置或修改imports.searchPath(这并不明显,因为它不会与for (x in imports)print(x) 一起显示)。所以这个:

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

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

    这与Seed 兼容,尽管imports 知道它有一个searchPath

    (此答案的早期版本准确性大大降低且更具煽动性。抱歉)。

    【讨论】:

      【解决方案2】:

      正如 Douglas 所说,您确实需要修改 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/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 函数后,您可以从入口点文件 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);
      

      喂!现在导入我们的库非常简单:

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

      【讨论】:

      • IME 堆栈行的格式略有变化;它现在包括第二个冒号和数字,大概是列号。我将正则表达式更改为/@(.+?)(?::\d+){1,2}/
      猜你喜欢
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 2019-12-30
      • 2013-03-05
      • 2010-09-25
      • 2012-12-17
      相关资源
      最近更新 更多