Запуск gists с помощью npx

Мы можем запускать gists с помощью npx. Я узнал об этом, прочитав вот это: https://nodejs.dev/learn/the-npx-nodejs-package-runner.

Я хочу запустить свой gist

Я создал gist, который печатает некоторый текст. Я выполнил команду, но она не сработала. Я решил, что мне нужен package.json, поэтому я добавил его и запустил команду, но она все равно не сработала. Я вспомнил, что мне нужен комментарий shebang и свойство bin. После их добавления и запуска все заработало. Вот полный gist:

code.js

#!/usr/bin/env node

console.log('Does that even work?');

// --------------------------------------------------
// To let npx run the gist we need
//
//   - package.json
//   - shebang comment at the top of file
//     - https://en.wikipedia.org/wiki/Shebang_(Unix)
//   - bin property in package.json
// --------------------------------------------------
Вход в полноэкранный режим Выход из полноэкранного режима

package.json

{
  "name": "npx-runs-gist",
  "description": "the gist to run it with npx command",
  "version": "0.1.0",
  "bin": "./code.js"
}
Войти в полноэкранный режим Выйти из полноэкранного режима

run-the-gist.bat

REM this is a comment in .bat files
REM runs the gist on Windows OS

npx https://gist.github.com/srele96/55260739ddef08389a2d992e132c843e
Войти в полноэкранный режим Выйти из полноэкранного режима

Использование библиотеки в gist

Вооружившись знаниями, я захотел использовать библиотеку. Это было просто. Я скопировал пример с сайта https://www.npmjs.com/package/commander. После этого я запустил его, и он заработал. В этот раз я потратил гораздо меньше усилий. Вот полный gist:

split.js

#!/usr/bin/env node

const { program } = require('commander');

program
  .option('--first')
  .option('-s, --separator <char>');

program.parse();

const options = program.opts();
const limit = options.first ? 1 : undefined;
console.log(program.args[0].split(options.separator, limit));
Вход в полноэкранный режим Выход из полноэкранного режима

package.json

{
  "name": "split",
  "version": "0.1.0",
  "description": "run split example from commander docs using gist and npx",
  "dependencies": {
    "commander": "9.4.0"
  },
  "bin": "./split.js"
}
Войти в полноэкранный режим Выйти из полноэкранного режима

run-the-gist.bat

REM intentionally misspeleld --fits
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --fits a/b/c

REM uses the correct flag --first
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / --first a/b/c

REM no flag 
npx https://gist.github.com/srele96/c4e645abd50c0b3c2e543c8557c044c9 -s / a/b/c
Войти в полноэкранный режим Выйти из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий