节点包 - 是否可以在package.json中插入变量?

hrs*_*ono 6 json command-line-interface node.js gruntjs

我有一个静态站点,使用编译Sass node-sass.

目前我正在使用Grunt来观看文件,但我觉得它太过分了,因为我可以使用它们的内置CLI.

所以我在package.json中添加:

// package.json
...
"scripts": {
  "sass": "node-sass -w input/dir -o output-dir/" 
}
Run Code Online (Sandbox Code Playgroud)

问题是,我需要require一个Sass框架模块(全局安装)--include-path.我可以在Gruntfile中执行此操作:

// Gruntfile.js
sass: {
  options: {
    includePaths: require("the-framework").includePaths()
  },
  ...
},
Run Code Online (Sandbox Code Playgroud)

所以我想到的第一件事是插入字符串,如:

// package.json
...
"scripts": {
  "sass": "node-sass -w input/dir -o output-dir/ --include-path " + require("the-framework").includePaths()
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,它不起作用.然后脚本运行,但插值变量被忽略.

任何解决方案或替代?如果可能的话,我宁愿不创建额外的文件来存储变量.

谢谢

Ale*_* B. 6

我不知道这是一种正确的方法,但我可以解释如何解决这个问题.

你不能插入变量package.json,因为它必须是有效的json.你可以在这里写bash命令.

1)您可以编写需要结果的节点命令.如果includePaths()不返回字符串,你应该小心.

Node options:
  -e, --eval script     evaluate script
  -p, --print           evaluate script and print result
Run Code Online (Sandbox Code Playgroud)

所以它会是这样的

node -e "console.log(require('the-framework').includePaths())"
Run Code Online (Sandbox Code Playgroud)

或更短的版本 --print

node -p "require('the-framework').includePaths()"
Run Code Online (Sandbox Code Playgroud)

2)将前一个命令内联输出到sass脚本中.照顾正确的逃脱.

{
  "scripts": {
      "sass": "node-sass -w input/dir -o output-dir/ --include-path $(node -p \"require('the-framework').includePaths()\")"
  }
}
Run Code Online (Sandbox Code Playgroud)

有关执行bash命令的更多信息,请点击此处.

PS Windows版本不同

{
  "scripts": {
      "sass": "FOR /f \"delims=\" %v IN ('node -p \"require('edje').includePaths()[0]\"') DO node-sass -w assets/sass -o assets/css --include-path \"%v\""
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到更多信息.