【问题标题】:Grunt - get current calling folder, and not gruntfile current folderGrunt - 获取当前调用文件夹,而不是 gruntfile 当前文件夹
【发布时间】:2023-03-22 16:57:01
【问题描述】:

如果我在某个文件夹 /foo 中安装了 Grunt,但我当前的文件夹是 /foo/bar/baz,并且我从当前文件夹中运行“grunt sometask”,我怎样才能获得 Grunt(或 NodeJS) ) 来确定我当前的路径?也就是说,如何以编程方式获取我调用 grunt 时所在的文件夹?

当我使用process.cwd()时,我得到了gruntfile的路径,即“foo”,这不是我想要的。

我不必专门在 Grunt 中执行此操作,任何基于 nodejs 的解决方案都可以工作。

【问题讨论】:

  • 恐怕 __dirname 或 __filename 都不起作用,它们返回当前脚本的位置,所以它仍然是 gruntfile 或 grunt 插件。

标签: javascript node.js gruntjs


【解决方案1】:

根据source code

默认情况下,所有文件路径都是相对于 Gruntfile 的

而且,this line of code 显示了 grunt 实际上如何将当前目录更改为 Gruntfile 的路径:

process.chdir(grunt.option('base') || path.dirname(gruntfile));

但是,选项--base 就是为此而存在的。参见文档:http://gruntjs.com/api/grunt.file

如果您不需要从内部 Gruntfile 执行此操作,只需运行捕获process.cwd() 然后execs grunt 的脚本。

见:https://www.npmjs.com/package/exec

var exec = require('exec');

process.cwd(); // Will have your current path

exec(['grunt', 'mytask'], function(err, out, code) {
  if (err instanceof Error)
    throw err;
  process.stderr.write(err);
  process.stdout.write(out);
  process.exit(code);
});

【讨论】:

  • 但这不是需要我用--base some_path调用grunt,然后手动调用grunt.file.setBase(some_path)吗?我不想设置当前路径,我想得到它。
  • 您当前的路径由 grunt 设置。当你得到它并输出 Gruntfile 所在的路径时,它是正确的。它不再是您调用 grunt 的地方。所以,如果你想强制它成为你调用的地方,你需要--base
  • 使用 --base 后需要一个路径值,请检查我的问题,这不是我要求的。此外,使用 --base 完全改变了 grunt 运行的位置上下文,我不想这样做,我只想读取路径。
  • 是的,您需要使用--base .。我明白你的问题。我想说的是:没有办法获得运行 Grunt 的路径因为 grunt 使用 chdir
  • 如果不需要从 grunt 内部获取路径,可以使用 exec 调用 grunt。我添加到答案中。
【解决方案2】:

在 Mac 或 Linex 中,您可以通过

process.env.PWD

在窗户里,未知

您可以编辑 grunt-cli 来完成此操作。

grunt-cli/bin/grunt

require(gruntpath).cli({_originDir:basedir});

然后在 gruntfile.js 中,你可以如下:

grunt.option('_originDir')

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2017-01-11
    • 1970-01-01
    • 2012-05-23
    • 2018-05-25
    • 2010-11-09
    相关资源
    最近更新 更多