How create npm package

How create npm package

Build and publish your first NPM package

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

What is NPM

NPM is a package manager for NodeJS. It was created in 2009 as an open source project to help javascript developers easily share code in form of packages. Since then thousands of packages have been published to the NPM registry where all the packages are hosted. This article will walk you through how you can create and publish your own NPM package.

What are we building/publishing

The focus of this article is not to build a bad-ass NPM package but instead to explain how to build and publish an NPM package. The build and publish cycle is nearly the same for any other package, once you understand how its done for something as simple as what we will be building in this article, you are good to go.
In this article, we will be building a random number generator, very simple hun… That’s the idea.

Building the package

Requirements

The single and most important file

The npm init command should reveal an interactive session in the CLI that looks like this:

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

You will be required to answer some questions, these questions are basically about the NPM package you want to create. The command line tool auto-suggests reasonable answers to the questions, if you feel the suggested answer is good enough, just hit enter. If you also don’t have an answer to any of the question, hit enter and continue, you can always edit it later.

After answering the questions, a package.json file will be created in the root of the project folder, the content will be similar to this:

Package.json is the single and most important file as far as creating/publishing an NPM package is concerned, without it, you won’t be able to publish whatever you create to the NPM registry.

Note the main field in the package.json file, it refers to the name of the file that would be loaded when your package is required by another application, by default it points to index.js

Adding the project codes

The project to be created is a very simple one, in fact, all the project code will be composed in a single file. Feel free to create something more complex.
Create an index.js file in the root of the project folder then add the code for the random number generator:

Notice the module.exports at the bottom of the file, whatever you are exporting here is what would be available for importing when others install the package.

Publishing the package

Authenticate

You need to create an account in the NPM registry, you can do this here. If you are having any issues creating an account check the documentation here.

Publish

Note that you may not be able to publish the random-number-package if someone else already has a package with the same name in the registry. You can simply change the name of the package to something unique to make it publishable. Check here for guides on naming a package.

Publishing your NPM package is as simple as entering this command in the CLI:

After the publish is done without any error, you can visit your account in the NPM registry to see the package.

Testing

To test the package, you simply need to install and use it. You can do the following to test the random-number-generator package:

Copy this simple test code and paste it in the test.js file.

Further reading

Adding a README to the project on NPM: Link

Creating a package.json file

Table of contents

You can add a package.json file to your package to make it easy for others to manage and install. Packages published to the registry must contain a package.json file.

A package.json file:

Note: To make your package easier to find on the npm website, we recommend including a custom description in your package.json file.

Required name and version fields

A package.json file must contain «name» and «version» fields.

The «name» field contains your package’s name, and must be lowercase and one word, and may contain hyphens and underscores.

The «version» field must be in the form x.x.x and follow the semantic versioning guidelines.

If you want to include package author information in «author» field, use the following format (email and website are both optional):

Creating a new package.json file

You can create a package.json file by running a CLI questionnaire or creating a default package.json file.

Running a CLI questionnaire

To create a package.json file with values that you supply, use the npm init command.

On the command line, navigate to the root directory of your package.

Run the following command:

Answer the questions in the command line questionnaire.

Customizing the package.json questionnaire

If you expect to create many package.json files, you can customize the questions asked and fields created during the init process so all the package.json files contain a standard set of information.

To add custom questions, using a text editor, add questions with the prompt function:

To learn more about creating advanced npm init customizations, see the init-package-json GitHub repository.

Creating a default package.json file

On the command line, navigate to the root directory of your package.

Run the following command:

Default values extracted from the current directory

Setting config options for the init command

You can set default config options for the init command. For example, to set the default author email, author name, and license, on the command line, run the following commands:

developers

Table of contents

So, you’ve decided to use npm to develop (and maybe publish/deploy) your project.

There are a few things that you need to do above the simple steps that your users will do to install your program.

About These Documents

These are man pages. If you install npm, you should be able to then do man npm-thing to get the documentation on a particular topic, or npm help thing to see the same information.

What is a Package

Even if you never publish your package, you can still get a lot of benefits of using npm if you just want to write a node program (a), and perhaps if you also want to be able to easily install it elsewhere after packing it up into a tarball (b).

Git urls can be of the form:

The package.json File

You need to have a package.json file in the root of your project to do much of anything with npm. That is basically the whole interface.

See package.json for details about what goes in that file. At the very least, you need:

name: This should be a string that identifies your project. Please do not use the name to specify that it runs on node, or is in JavaScript. You can use the «engines» field to explicitly state the versions of node (or whatever else) that your program requires, and it’s pretty well assumed that it’s JavaScript.

It does not necessarily need to match your github repository name.

So, node-foo and bar-js are bad names. foo or bar are better.

version: A semver-compatible version.

engines: Specify the versions of node (or whatever else) that your program runs on. The node API changes a lot, and there may be bugs or new functionality that you depend on. Be explicit.

author: Take some credit.

scripts: If you have a special compilation or installation script, then you should put it in the scripts object. You should definitely have at least a basic smoke-test command as the «scripts.test» field. See scripts.

main: If you have a single module that serves as the entry point to your program (like what the «foo» package gives you at require(«foo»)), then you need to specify that in the «main» field.

directories: This is an object mapping names to folders. The best ones to include are «lib» and «doc», but if you use «man» to specify a folder full of man pages, they’ll get installed just like these ones.

You can use npm init in the root of your package in order to get you started with a pretty basic package.json file. See npm init for more info.

Keeping files out of your Package

If you want to double check that your package will include only the files you intend it to when published, you can run the npm pack command locally which will generate a tarball in the working directory, the same way it does for publishing.

Before Publishing: Make Sure Your Package Installs and Works

This is important.

If you can not install it locally, you’ll have problems trying to publish it. Or, worse yet, you’ll be able to publish it, but you’ll be publishing a broken or pointless package. So don’t do that.

In the root of your package, do this:

That’ll show you that it’s working. If you’d rather just create a symlink package that points to your working directory, then do this:

To test a local install, go into some other folder, and then do:

to install it locally into the node_modules folder in that other place.

Then go into the node-repl, and try using require(«my-thing») to bring in your module’s main module.

Create a User Account

Create a user with the adduser command. It works like this:

and then follow the prompts.

This is documented better in npm adduser.

Publish your Package

This part’s easy. In the root of your folder, do this:

You can give publish a url to a tarball, or a filename of a tarball, or a path to a folder.

Send emails, write blogs, blab in IRC.

Tell the world how easy it is to install your program!

Creating and publishing scoped public packages

Table of contents

To share your code publicly in a user or organization namespace, you can publish public user-scoped or organization-scoped packages to the npm registry.

For more information on scopes, see «About scopes».

Note: Before you can publish user-scoped npm packages, you must sign up for an npm user account.

Additionally, to publish organization-scoped packages, you must create an npm user account, then create an npm organization.

Creating a scoped public package

If you are using npmrc to manage accounts on multiple registries, on the command line, switch to the appropriate profile:

On the command line, create a directory for your package:

Navigate to the root directory of your package:

If you are using git to manage your package code, in the package root directory, run the following commands, replacing git-remote-url with the git remote URL for your package:

In the package root directory, run the npm init command and pass the scope to the scope flag:

For an organization-scoped package, replace my-org with the name of your organization:

For a user-scoped package, replace my-username with your username:

Respond to the prompts to generate a package.json file. For help naming your package, see «Package name guidelines».

Create a README file that explains what your package code is and how to use it.

In your preferred text editor, write the code for your package.

Reviewing package contents for sensitive or unnecessary information

Publishing sensitive information to the registry can harm your users, compromise your development infrastructure, be expensive to fix, and put you at risk of legal action. We strongly recommend removing sensitive information, such as private keys, passwords, personally identifiable information (PII), and credit card data before publishing your package to the registry.

Testing your package

To reduce the chances of publishing bugs, we recommend testing your package before publishing it to the npm registry. To test your package, run npm install with the full path to your package directory:

Publishing scoped public packages

On the command line, navigate to the root directory of your package.

To publish your scoped public package to the npm registry, run:

To see your public package page, visit https://npmjs.com/package/\*package-name\*, replacing * package-name * with the name of your package. Public packages will say public below the package name on the npm website.

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

For more information on the publish command, see the CLI documentation.

How to Create an npm Package Ready to Distribute From Scratch

What Is npm and Why Is It Important?

Node Package Manager, or npm (usually written in lower case) is one of the most commonly used package managers in JavaScript projects. It is built on top of Node and is so powerful that nearly everybody is using it.

What Is A Package Manager?

Imagine that you include library A to customize a text field. That library uses library B to format text and library C to show translations.

Imagine that, at the same time, library C uses another five different libraries to handle different languages and you end up with a scheme like this one.

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

That’s called the dependency tree of your application.

Sooner or later your project will end up with dozens of dependencies (you won’t even be aware of some of them). And what’s even worse, each of those dependencies will only be compatible with certain specific versions.

This situation would be a nightmare to manage manually. A simple update in a submodule might break your dependency tree and your app might not compile. That’s exactly the problem that npm solves.

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

When you create an npm library you will create a json file called package.json in which you specify which dependencies your JS library has.

At the same time, the dependencies of your library will have their own package.json files, creating a full dependency tree.

If someone wants to add your library to their project, then they will just need to run:

Magically, all the dependencies of the tree will be downloaded and installed. This system is amazing because in practice you don’t need to care about the dependencies at all.

Is There Any Downside of Using a Package Manager?

The main one is that developers lose control of which code they are including in their projects. Concerns about security have arisen in the past and critical systems require a very controlled and strict dependency tree.

Take this example: a newly created project in React Native has more than 1500 dependencies. It is unlikely that more than a few people know them all. If someone introduced some malicious code – or just a bug – a lot of developers would probably adopt this code without even knowing it.

Don’t worry. This is a very rare occurrence. However it has already happened a few times.

Another example is the dispute in 2019 between an open-source developer and an American company that almost broke the world’s internet. Long story short, the developer decided to remove a quite-trivial-yet-often-used library from npm and suddenly the dependency tree of thousands of projects around the world was broken.

Why Should You Create Your Own npm Package Libraries?

The fastest and safest way to write code is by not writing it. If you usually need to copy-paste some features among different projects, you might prefer to create a new JavaScript library and write those features only once.

Then, the next time you need to use those features, you don’t need to copy-paste or write them again – you just reuse your library. What’s more, if you find a bug, you can solve it once and distribute the fix to the rest of your projects.

Once you have written your node module, one of the easiest and fastest ways to include them in your projects is by using npm.

That’s exactly what we thought when we introduced the remote logger BugfenderJS. Our SDK can be included manually, but most of our users just install it using npm:

Creating Your Own npm Package

1. Create a New Git Repository

If you’ve already created some code you can skip this part. If you are starting from scratch, however, it is time to git init. Then you can go to GitHub and create a new git repo.

2. Create your package file

Now open the terminal and navigate to your project

This tool will help you to create a new package.json asking you for the basic data needed. Some quick tips:

Start Fixing Bugs Faster Now for Free

Bugfender is the best remote logger for mobile apps.

If you don’t want to fill the rest of the fields now, you can skip them and come back later to add them in the package.json file.

How create npm package. Смотреть фото How create npm package. Смотреть картинку How create npm package. Картинка про How create npm package. Фото How create npm package

3. Adding Code To Your JavaScript Project and Establishing The Public API

Usually you have some code that you have been copy-pasting between various projects and you’re moving it to an npm module to reuse it in the future.

If that’s the case, now it’s time to add this code to the npm project. Next you will need to think of the API that you will expose to the world.

Define Your Public API With module.exports

Then, your code will go to the index.js and will ascertain the value of the module. For example, if inside your index.js you set:

Then coffeMachine will be a number with value 42.

A more realistic approach would be to set this value to an instance of a class:

coffeeMachine is now an instance of BugfenderCoffeeMachine and you can now do:

Add a README.md File

The easiest and trivial step is also one of the most important. Having a good Readme file ensures that other people will be able to understand what your library’s about – and how to use it.

You don’t need to be too creative about it, just use a template like this one and try to fill all the fields in a clear way.

The users of your npm library will appreciate that you saved them time. Even a future version of you will be happy to have clear docs!

Commit

Now your library is ready and you can proceed with your first commit.

Similar to the Readme file, there are already plenty of docs on how to write meaningful git commits.

4. Publish on npm

Sign up to npm

If you don’t have a npm account, it’s time to sign up.

npm is a command line tool. Open the console and write:

You can check that you are correctly logged in with

Tip: prior to publishing a new npm package, ensure that you are logged with the adequate user. This is especially important if you use the same machine for work and side projects.

Test Your Framework

We are almost ready to publish. But just before we do, we can run a quick local test.

You can use this process in the future when you plan to update your library so you don’t need to publish every time you want to test new changes.

Publish

Now that you’ve created the library and you tested it locally, it’s time to share it with the world.

npm will start to work on publishing your library to the official repository.

When it finishes, the library should be available in https://www.npmjs.com and every user in the world should be able to install it using npm install

5. Updating your library

We’re arriving at the end of the article, but it’s only the beginning of your library.

If you start using it and other users adopt it, you will also need to maintain it. From time to time you will have to introduce new features or update deprecated code. Whenever you do that, remember to use Semantic Versioning (major.minor.patch).

npm eases the process of maintaining your code with the npm versioning tools:

One Last Thing

At Bugfender we are software developers ourselves and we know how valuable these guides are. If you found this post helpful, you can help us in return by sharing it with your colleagues.

Bugfender is the remote console logger created for developers, by developers. The new Javascript SDK helps you to find bugs faster and provide even better customer support to your clients.

You can sign up for free in less than 20 seconds and add the SDK to your site in an additional 10 seconds using npm install @bugfender/sdk (not bad for half a minute ;-).

We publish tutorials and debugging stories regularly on our blog. Don’t forget to visit us from time to time or, even better, subscribe to our quarterly spam-free newsletter to get an overview of the new articles.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *