Содержание
Helper Methods
Adds item to the array at the beginning of it.
importupdatefrom'update-js';constobj={ foo{ bar1,2}};constupd=update.unshift(obj,'foo.bar',3);upd.foo.bar
Alias:
Adds item to the array.
importupdatefrom'update-js';constobj={ foo{ bar1,2}};constupd=update.push(obj,'foo.bar',3);upd.foo.bar
Alias:
Removes item from the array by index or lookup key.
importupdatefrom'update-js';constobj={ foo{ bar1,2,3,4}};constupd=update.remove(obj,'foo.bar.1');upd.foo.bar
With lookup key:
constobj={ foo{ items{ id1, bar2},{ id2, bar3},{ id3, bar4}}}constupd=update.remove(obj,'foo.items.{id:2}');upd.foo.items
Note that this helper cannot be used to remove item from array if the latter is used as target object, i.e. won’t work.
Assigns properties of the given object to the one specified by the path.
importupdatefrom'update-js';constobj={ foo{ bar{ baz'bak'}}};constupd=update.assign(obj,'foo.bar',{ bak'baz'});upd.foo.bar
Deletes object property at specified path.
importupdatefrom'update-js';constobj={ foo{ bar{ baz'bak', bak'baz'}}};constupd=update.del(obj,'foo.bar.baz');upd.foo.bar
Note that this helper cannot be used to delete property for target object itself, i.e. won’t work.
Support Features
-
all types of npm package
- a) a folder containing a program described by a package.json file ()
- b) a gzipped tarball containing (a) ()
- c) a url that resolves to (b) ()
- d) a @ that is published on the registry with (c)
- e) a @ (see npm-dist-tag) that points to (d)
- f) a that has a «latest» tag satisfying (e)
- g) a that resolves to (a) ()
- All platform support
- global install ()
- , , scripts
- node-gyp
- bin (yo@1.6.0, fsevents@1.0.6)
- scoped package
- bundleDependencies / bundledDependencies (node-pre-gyp@0.6.19, fsevents@1.0.6)
- optionalDependencies (pm2@1.0.0)
- peerDependencies (co-defer@1.0.0, co-mocha@1.1.2, estraverse-fb@1.3.1)
- deprecate message
- mode
- , ,
- support
- uninstall
- resolutions
Управление модулями npm¶
Модули — это приложения, которые реализовывают некоторый функционал и могут быть использованы для разработки более сложных приложений. Например, фреймворк Express является устанавливаемым модулем. Рассмотрим установку пакета на примере Express. Из корневой директории проекта необходимо выполнить команду.
Все модули устанавливаются в директорию той директории, откуда была вызвана команда .
Флаг указывает на то, что мы хотим внести данный модуль в список зависимостей в файл . И когда возникнет необходимость запустить приложение в другой среде, то совсем не обязательно также переносить и папку . Перенесите только файл и выполните в командной строке.
И все указанные в Node.js npm модули будут установлены в папку .
Если при установке пакета вы не хотите, чтобы он добавлялся в список зависимостей, то просто не указывайте флаг .
После установки модуля с в появится объект со списком зависимостей вашего проекта.
package.json
Для задания установки определенной версии или версии из какого-либо диапазона, используйте оператор .
При указании диапазона версий задаваемое значение должно быть заключено в двойные кавычки.
Установка самой последней версии модуля может быть выполнена так.
В процессе разработки, например для тестирования или измерения показателей производительности, вам могут понадобиться Node.js npm модули, которые не будут использоваться и даже не должны устанавливаться в среде . Чтобы установить npm модуль только для среды разработки, укажите флаг .
Теперь в должен появиться новый блок .
package.json
Теперь рассмотрим глобальную установку пакетов. Допустим, на вашем сервере одновременно работают несколько разных Node.js приложений, но которые имеют общие зависимости. Чтобы не дублировать пакет в директории каждого проекта, вы можете установить его в вашу систему глобально с помощью флага и он будет доступен для использования во всей системе.
С течением времени Node.js npm модули дорабатываются и улучшаются, а следовательно выходят их новые версии. Чтобы обновить все пакеты, описанные в , используйте такую команду.
Обновление конкретного модуля, например Express, выглядит так.
Для удаления пакет из зависимостей вашего проекта, используйте .
Если вы хотите также удалить его из , просто укажите флаг .
Benchmarks
- npminstall@1.2.0
- pnpm@0.18.0
- npm@2.14.12
cli | real | user | sys |
---|---|---|---|
npminstall | 0m10.908s | 0m8.733s | 0m4.282s |
npminstall with cache | 0m8.815s | 0m7.492s | 0m3.644s |
npminstall —no-cache | 0m10.279s | 0m8.255s | 0m3.932s |
pnpm | 0m13.509s | 0m11.650s | 0m4.443s |
npm | 0m28.171s | 0m26.085s | 0m8.219s |
npm with cache | 0m20.939s | 0m19.415s | 0m6.302s |
npminstall babel-preset-es2015 browserify chalk debug minimist mkdirp real 0m8.929s user 0m5.606s sys 0m2.913s
pnpm i babel-preset-es2015 browserify chalk debug minimist mkdirp real 0m12.998s user 0m8.653s sys 0m3.362s
npm i babel-preset-es2015 browserify chalk debug minimist mkdirp real 1m4.729s user 0m55.589s sys 0m23.135s
Файл package.json¶
Для более удобного управления конфигурацией и пакетами приложения в npm применяется файл конфигурации . Так, добавим в папку проекта новый файл :
Здесь определены только две секции: имя проекта — и его версия — . Это минимально необходимое определение файла . Данный файл может включать гораздо больше секций. Подробнее можно посмотреть в документации.
Далее удалим из проекта каталог . То есть в папке проекта будут два файла и .
Теперь снова добавим с помощью следующей команды:
Флаг указывает, что информацию о добавленном пакете надо добавить в файл .
И после выполнения команды, если мы откроем файл , то мы увидим информацию о пакете:
Информация обо всех добавляемых пакетах, которые используются при запуске приложения, добавляется в секцию .
Файл играет большую роль и может облегчить разработку в различных ситуациях. Например, при размещении в разных репозиториях нередко мы ограничены выделяемым дисковым пространством, тогда как папка со всеми загруженными пакетами может занимать довольно приличное пространство. В этом случае удобнее разместить основной код проекта без . В этом случае мы можем определить все пакеты в файле , а затем для загрузки всех пакетов выполнить команду
Эта команда возьмет определение всех пакетов из секций и загрузит их в проект.
Usage
importupdatefrom'update-js';constobj={ foo{ bar{ baz1},{ baz2}}, bak{ barbaz1}};constupd=update(obj,'foo.bar.1.baz',3);upd.foo.bar1.baz===3;upd !== obj;upd.foo!==obj.foo;upd.foo.bar!==obj.foo.bar;upd.foo.bar===obj.foo.bar;upd.foo.bar1!==obj.foo.bar1;upd.bak===obj.bak;
By passing object instead of string path you can update multiple values with one operation. In this case object keys are used as paths at which corresponding object values should be assigned.
constobj={ foo{ bar'baz'}, baz{ bak'foo'}};constupd=update(obj,{'foo.bar''baz2','foo.baz.0.bak''foo2'});upd.foo.barupd.foo.baz.bak
constobj={ footrue, bar{ baz1,2, bak{ a'a1'},{ a'a2'}}};constupd=update(obj,{ foofalse,'bar.baz'update.push(3),'bar.bak.{a:a2}'update.assign({ b'b2'})});upd
You can use function that accepts updater function instead of value. The current value at the path is passed as only argument to this function:
constobj={ foo{ bar1,2,3,4}, bak{ barbaz1}};constupd=update.with(obj,'foo.bar',(old)=>old.filter(i=> i %2===));upd.foo.bar
Be careful not to update old object in place when using updater function.
Lookup keys are used to index objects in array by their property values. For example:
importupdatefrom'update-js';constobj={ foo{ items{ id1, bar2},{ id2, bar3},{ id3, bar4}}}constupd=update(obj,'foo.items.{id:2}.bar',5);upd.foo.items1.bar===5
Notes on object lookup:
- Object auto-generation is not supported when using path with object lookup, i.e. both collection and object specified by lookup key should exist. If no object exists, update action will be ignored.
- Lookup should be used with simple values since it uses comparison.
- It is possible to specify several lookup fields, like .
When encounters lookup key that doesn’t correspond to any object in collection, it invokes handler, passing collection and lookup key to that function. There may be different strategies for handling such cases, depending on execution environment and your needs.
provides 3 predefined handlers, available from :
importupdatefrom'update-js';import{warnOnMissing,throwOnMissing,noop}from'update-js/utils';update.onLookupMissingObject= warnOnMissing;update.onLookupMissingObject= throwOnMissing;update.onLookupMissingObject= noop;
The default value for is .
Release History
- : for new features
- : for changes in existing functionality
- : for once-stable features removed in upcoming releases
- : for deprecated features removed in this release
- : for any bug fixes
Custom labels used in this changelog:
- : bumps dependencies
- : code re-organization, minor edits, or other changes that don’t fit in one of the other categories.
Heads up!
fixed
ensure app.cwd in the current instance is the cwd defined by the user on the options or argv.
added
- adds support user-defined templates
- adds support for , which resolves to or the user-defined . This directory is used to determine the base directory for user-defined templates.
- adds experimental support for a updater. If an exists in the directory (this will be customizable, but it’s not yet), this file will be loaded and d as a plugin before other updaters are loaded. You can use this to set options, add defaults, etc. But you can also run it explictly via commandline with the command.
fixed
- fixes so that it’s updated when () is set
- ensure args are parsed consistently
First stable release!
$ update help Usage: update <command> Command: updater or tasks to run Options: --config, -c Save a configuration value to the `update` object in package.json --cwd Set or display the current working directory --help, -h Display this help menu --init, -i Prompts you to choose the updaters to automatically run (your "queue") --add Add updaters to your queue --remove Remove updaters from your queue --run Force tasks to run regardless of command line flags used --silent, -S Silence all tasks and updaters in the terminal --show <key> Display the value of <key> --version, -V Display the current version of update --verbose, -v Display all verbose logging messages Examples: # run updater "foo" $ update foo # run task "bar" from updater "foo" $ update foo:bar # run multiple tasks from updater "foo" $ update foo:bar,baz,qux # run a sub-generator from updater "foo" $ update foo.abc # run task "xyz" from sub-generator "foo.abc" $ update foo.abc:xyz Update attempts to automatically determine if "foo" is a task or updater. If there is a conflict, you can force update to run updater "foo" by specifying its default task. Example: `$ update foo:default`
Use as Cli
$ npm install npminstall -g
$ npm install cnpm -g$ cnpm install // will use npminstall
Usage: npminstall npminstall <pkg> npminstall <pkg>@<tag> npminstall <pkg>@<version> npminstall <pkg>@<version range> npminstall <folder> npminstall <tarball file> npminstall <tarball url> npminstall <git:// url> npminstall <github username><github project>Can specify one or more: npm install ./foo.tgz bar@stable /some/folderIf no argument is supplied, installs dependencies from ./package.json.Options: --production: won't install devDependencies --save, --save-dev, --save-optional: save installed dependencies into package.json -g, --global: install devDependencies to global directory which specified in `$ npm config get prefix` -r, --registry: specify custom registry -c, --china: specify in china, will automatically using chinese npm registry and other binary's mirrors -d, --detail: show detail log of installation --trace: show memory and cpu usages traces of installation --ignore-scripts: ignore all preinstall / install and postinstall scripts during the installation --no-optional: ignore optionalDependencies during the installation --forbidden-licenses: forbit install packages which used these licenses --engine-strict: refuse to install (or even consider installing) any package that claims to not be compatible with the current Node.js version. --flatten: flatten dependencies by matching ancestors dependencies --registry-only: make sure all packages install from registry. Any package is installed from remote(e.g.: git, remote url) cause install fail. --cache-strict: use disk cache even on production env
Usage: npmuninstall <pkg> npmuninstall <pkg>@<version> npmuninstall <pkg>@<version><pkg>@<version>
Usage: npmlink <folder>
Семантическое версионирование¶
При определении версии пакета применяется семантическое версионирование. Номер версии, как правило, задается в следующем формате . Если в приложении или пакете обнаружен какой-то баг и он исправляется, то увеличивается на единицу число . Если в пакет добавляется какая-то новая функциональность, которая совместима с предыдущей версией пакета, то это небольшое изменение, и увеличивается число . Если же в пакет вносятся какие-то большие изменения, которые несовместимы с предыдущей версией, то увеличивается число . То есть глядя на разные версии пакетов, мы можем предположить, насколько велики в них различия.
В примере с express версия пакета содержала, кроме того, дополнительный символ карет: . Этот символ означает, что при установке пакета в проект с помощью команды будет устанавливаться последняя доступная версия от . Фактически это будет последняя доступная версия в промежутке от до ( и ). Более подробно про сематическое версионирование в можно посмотреть здесь.
update-js/fp Module
Aside from main functionality of function, also provides module. The function imported from it generates a transformation-currying function that accepts a subject of update as it’s only argument. It can be used as a callback for some state-updater function. For example, one may have something like:
importupdatefrom'update-js/fp';setState(update('foo.bar.baz',5));
function has the same helper methods as it’s counterpart, for example:
importupdatefrom'update';importupdateFpfrom'update/fp';update.add(state,'list.items', obj);updateFp.add('list.items', obj)(state);
NOTE: if you want to use update helpers in multi-key updates, you have to use the ones provided by base package.
Команды npm¶
NPM позволяет определять в файле команды, которые выполняют определенные действия. Например, определим следующий файл :
В данном случае мы получаем переданные при запуске приложению параметры.
И определим следующий файл :
Здесь добавлена секция , которая определяет две команды. Вообще команд может быть много в соответствии с целями и задачами разработчика.
Первая команда называется . Она по сути выполняет команду , которая выполняет код в файле
Вторая команда назвывается . Она также выполняет тот же файл, но при этом также передает ему два параметра.
Названия команд могут быть произвольными. Но здесь надо учитывать один момент. Есть условно говоря есть зарезервированные названия для команд, например, , , и ряд других. Их не очень много. И как раз первая команда из выше определенного файла называется . И для выполнения подобных команд в терминале/командной строке надо выполнить команду
Например, для запуска команды
Команды с остальными названия, как например, в вышеопределенном файле, запускаются так:
Например, последовательно выполним обе команды:
Overview
All updating is accomplished using plugins called updaters, which are run by command line or API, and can be installed globally, locally, or created in a local .
- create continuity and consistency across projects
- enforce conventions across all of your projects
- instantly update an old or inherited project to your latest personal preferences (convert tabs to spaces, convert from to or the other way around, or any other detail)
- reformat code to meet your standards
- convert a config file to a different format (json to yaml, yaml to json, etc)
- update files that are typically excluded from build cycles, and are often forgotten about after they’re created. For example:
- be more productive: Update eliminates time spent on things that can be automated, but typically aren’t since they either don’t need to be done often, don’t fit into the build cycle or a project’s deliverables, or because they’re usually updated manually. As code projects mature, time spent on these things tend to stay linear or increase as the size of a community grows. If you maintain more than a handful of projects, time spent on these things compounds with each new project under your stewardship.
- well tested: with more than 1,250 unit tests
Here are some random example commits after running .
Project/Commit | Updaters used
- render templates: use templates to create new files, or replace existing files
- prompts: It’s easy to create custom prompts. Answers to prompts can be used as context for rendering templates, for settings options, determining file names, directory structure, and anything else that requires user feedback.
- data: gather data from the user’s environment to populate «hints» in user prompts or for rendering templates
- stores: persist configuration settings, global defaults, project-specific defaults, answers to prompts, and so on.
- much more!
С этим читают
- Как использовать оператор use и функцию целочисленного деления в php 7
- Json в python
- Postcss-loader
- Php serialize() function
- Uri
- Обновление sql server с помощью мастера установки (программа установки)upgrade sql server using the installation wizard (setup)
- Php: pdo быстрый старт, работа с mysql
- Math
- Руководство по аутентификации в node.js без passport.js и сторонних сервисов
- Мега-учебник flask, часть 4: база данных (издание 2018)