构建
想创建可执行脚本的话,需要在 package.json
文件中添加 bin
字段。
"bin": {
"grepjs": "dist/bin/cmd.js"
}
该字段将想要的执行名(grepjs
)指向你的入口脚本(如:dist/bin/cmd.js
)。
为了保证 dist/bin/cmd.js
是可执行的,需使用 chmod
命令:
chmod +x dist/bin/cmd.js
执行如下命令来全局安装该包。它使得 grepjs
成为在全系统内可执行的命令。
npm install -g
记得在 package.json
文件所在的根目录执行该命令。
安装后,可执行如下操作:
grepjs -n line lib/*ts
执行结果如下:
3: import * as readline from 'readline'
16: const lines = filePath === '' ? await _readStdinLines() : await _readFileLines(filePath)
21: matchingLines = _filterLines(regex, lines, false)
23: matchingLines = _filterLines(regex, lines, true)
73: (count, lines) => count + lines.length,
78: function _filterLines (regexPattern: RegExp, lines: string[], flag: boolean): MatchItem[] {
79: const candidates: MatchItem[] = lines.map((line, index) => [index + 1, line.trim()])
81: .filter(([_, line]) => regexPattern.test(line) === flag)
100: const rl = readline.createInterface({
107: const lines: string[] = []
108: rl.on('line', (line) => {
113: resolve(lines)
尝试递归搜索:
grepjs -nr line lib/ bin/
结果:
lib/grep.ts:
3: import * as readline from 'readline'
16: const lines = filePath === '' ? await _readStdinLines() : await _readFileLines(filePath)
21: matchingLines = _filterLines(regex, lines, false)
23: matchingLines = _filterLines(regex, lines, true)
73: (count, lines) => count + lines.length,
78: function _filterLines (regexPattern: RegExp, lines: string[], flag: boolean): MatchItem[] {
79: const candidates: MatchItem[] = lines.map((line, index) => [index + 1, line.trim()])
81: .filter(([_, line]) => regexPattern.test(line) === flag)
100: const rl = readline.createInterface({
107: const lines: string[] = []
108: rl.on('line', (line) => {
113: resolve(lines)
bin/cmd.ts:
8: // Parse command-line options
14: describe: 'Only a count of selected lines is written to standard output.',
32: alias: 'line-number',
34: 'Each output line is preceded by its relative line number in the file, starting at line 1. The line number counter is reset for each file processed. This option is ignored if -c is specified.',
47: 'Selected lines are those not matching any of the specified patterns.',
75: printResult(result, argv['line-number'] as boolean)
86: for (const [filePath, lines] of Object.entries(result)) {
87: for (const [lineNumber, line] of lines) {
93: console.log(`${lineNumber}: ${line}`)
95: console.log(line)
此刻,你可能有太多命令(运行、测试、本地安装、构建等)要记。可以选择添加一个 Makefile 来帮助构建。
Makefile:
.PHONY: run test lint build publish clean
run:
npm start
test:
npm test
lint:
npm run lint
install:
chmod +x dist/bin/cmd.js
npm install -g
build:
npm run build
publish: build
npm publish
clean:
rm -rf dist
然后,你可以轻松地执行这些操作:
make run
make test
make build
make install
make publish