节点包 – 是否有可能在package.json中插入一个variables?

我有一个使用node-sass编译Sass的静态网站。

目前我正在使用Grunt来观看文件,但是我觉得这是过度的,因为我可以使用他们的内置CLI。

所以我把这个添加到我的package.json中:

 // package.json ... "scripts": { "sass": "node-sass -w input/dir -o output-dir/" } 

问题是,我需要在--include-path require一个Sass框架模块(全局安装)。 我可以在Gruntfile中做到这一点:

 // Gruntfile.js sass: { options: { includePaths: require("the-framework").includePaths() }, ... }, 

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

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

和预期的一样,这是行不通的。 那么脚本运行,但插值的variables被忽略。

任何解决scheme或替代? 如果可能的话,我宁愿不创build额外的文件来存储variables。

谢谢

我不知道这样做是否正确,但我可以解释我将如何解决这个任务。

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

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

 Node options: -e, --eval script evaluate script -p, --print evaluate script and print result 

所以会是这样的

 node -e "console.log(require('the-framework').includePaths())" 

或者用--print更短的版本

 node -p "require('the-framework').includePaths()" 

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

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

有关执行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\"" } } 

更多信息你可以在这里find。

你可以这样:

 “scripts”: { “sass”: “node-sass --include-path scss scss/main.scss public/css/main.css” }, 

有很多方法可以用npm脚本来解决这个问题。

通过查看您的具体需求,我首先想到的是,npm在调用脚本时接受额外的参数。 例如:

 npm run sass -- path/to/the-framework 

这将解决:

 node-sass -w input/dir -o output-dir/ --include-path path/to/the-framework 

另一种方法是将代码移动到.js可执行文件(Node)中,我们将其称为watch-sass.js

所以你的脚本看起来像:

 "sass": "node watch-sass.js" 

你会运行:

 npm run sass 

这样你就有更多的自由去做你想要的任何东西在你的文件中。


可能性是无限的,如果你愿意的话,你可以利用bash脚本而不是JS的力量,它们都可以读/写环境variables。 但是你不一定需要它们。 例如,你可以有一个shell脚本,为你(或者Python,或者Ruby …)写一个package.json,并且已经有了所有的variables。 但最终我认为这只是一个口味的问题,使用你觉得更简单或更舒适的使用。