如何使用npm
脚本和postinstall
挂钩显示npm
软件包的许可证。现在,我正在使用:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"postinstall": "cat ./MIT-license.txt"
},
在package.json
。但这在Windows上失败了,因为cat
。我知道我们可以type
在Windows上使用它来通过控制台输出文件的内容,但是如何在npm脚本中做到这一点(cat
在Windows和type
Unix / mac上不会失败)?
如果我理解正确,则需要跨平台机制将文件内容记录到控制台。我认为最简单的方法是通过自定义Node脚本,因为您知道无论使用什么操作系统,用户都将安装Node。
只需编写如下脚本:
// print-license.js
'use strict';
const fs = require('fs');
fs.readFile('./MIT-license.txt', 'utf8', (err, content) => {
console.log(content);
});
然后,在您的package.json中:
// package.json
"scripts": {
"postinstall": "node ./print-license.js"
},
或者,如果您不希望出现一个分散的脚本,那么它足够短以进行内联,如下所示:
// package.json
"scripts": {
"postinstall": "node -e \"require('fs').readFile('./MIT-license.txt', 'utf8', function(err, contents) { console.log(contents); });\""
},
现在,考虑到这一点,使用可重用的可执行文件可能会更好,该可执行文件允许您将文件指定为命令行参数。这也很简单:
// bin/printfile
#!/usr/bin/env node
'use strict';
const FILE = process.argv[2];
require('fs').readFile(FILE, 'utf8', (err, contents) => {
console.log(contents);
});
并将以下内容添加到package.json中:
// package.json
"bin": {
"printfile": "./bin/printfile"
},
"scripts": {
"postinstall": "printfile ./MIT-license.txt"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句