How to Create and Publish an npm Package
- Initial Setup. Create a.gitignore file to exclude the node_modules folder.
- Writing the code. Let’s understand the code first.
- Executing the code.
- Testing the created npm package using require statement.
- Testing the created npm package using the import statement.
Create a package. json file
- To create a package. json file, on the command line, in the root directory of your Node. js module, run npm init :
- Provide responses for the required fields ( name and version ), as well as the main field: name : The name of your module. version : The initial module version.
npx create-react-native-library react-native-awesome-module. Copy. Where react-native-awesome-module is the name you would like for the new module. After doing this you will navigate into react-native-awesome-module folder and bootstrap the example project by running: yarn.
How do I link a package to another package in NPM?
What is the best way to develop NPM projects locally?
You need a way to reference the package locally while you’re developing it. You could run npm install with the absolute path to the package. If you need to test out pre-install/post-install hooks in your package then you will want to use this approach. If you don’t care about the best way to develop NPM projects locally is by using npm link.
How do I package npm?
- Created an NPM Account from npmjs.org.
- Login to the terminal using your npm credentials using the command, npm login.
- Initialized the package. json file using the npm init -y command.
- Wrote code.
- Deployed the package using, npm publish.
- Use your deployed package using npm i
How do I create and publish my own npm package?
- Step 1 — Initial Setup.
- Step 2 — Writing the code.
- Step 3 — Executing the code.
- Step 4 — Testing the created npm package using require statement.
- Step 5 — Testing the created npm package using the import statement.
- Step 6 — Publish to the npm repository.
- Step 7 — Semantic versioning in npm.
How npm create package json?
json file using npm init, but you can also create one automatically. Creating a package. json file is typically the first step in a Node project, and you need one to install dependencies in npm.
Create package. json
- Enter the root folder of your project.
- Run npm init.
- Fill out the prompts to create your package. json.
How do I create a project in npm?
- First create a directory for your new application and navigate into it:
- Use the npm init command to create a package.json file for your application.
- Now install Express in the myapp directory and save it in the dependencies list of your package.json file.
- npm install express.
What is npm package?
How do I make a package public?
To publish a scoped package with public visibility, use npm publish –access public.
- On the command line, navigate to the root directory of your package. cd /path/to/package.
- To publish your scoped public package to the npm registry, run: npm publish –access public.
What is a scoped npm package?
Scopes are a way of grouping related packages together, and also affect a few things about the way npm treats the package. Each npm user/organization has their own scope, and only you can add packages in your scope. This means you don’t have to worry about someone taking your package name ahead of you.
What is the name of the npm package?
How do I initiate a json 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. cd /path/to/package.
- Run the following command: npm init.
- Answer the questions in the command line questionnaire.
How do I install npm packages?
To install a package, npm uses the following algorithm:
- load the existing node_modules tree from disk.
- clone the tree.
- fetch the package.json and assorted metadata and add it to the clone.
- walk the clone and add any missing dependencies.
- dependencies will be added as close to the top as is possible.
What is npm package json?
The package. json file is the heart of any Node project. It records important metadata about a project which is required before publishing to NPM, and also defines functional attributes of a project that npm uses to install dependencies, run scripts, and identify the entry point to our package.
What is scripts in package json?
Scripts are stored in a project’s package. json file, which means they’re shared amongst everyone using the codebase. They help automate repetitive tasks, and mean having to learn fewer tools. Node npm scripts also ensure that everyone is using the same command with the same flags.
What is package-lock json?
package-lock. json is automatically generated for any operations where npm modifies either the node_modules tree, or package. json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
How do I make a react package?
A React app. I created the boilerplate for this article with npx create-react-app npm-test. Run the app on your local machine.
Run the app on your local machine.
- Create and isolate components to publish.
- Install Babel and build the dist folder.
- Alter the package.
- Use the new package.
How to create and publish a npm package?
– Make a fresh project directory. – In the terminal, type npm init to initialize the Node project. – Now do npm install gfgnpmpkgupload to download the npm module that we just made. – Now everything is set, lets try to run node.js file and see if our module is correctly uploaded, published, imported in our new project, and used.
How to install npm packages manually?
npm install (in package directory, no arguments): Install the dependencies in the local node_modules folder. In global mode (ie, with -g or –global appended to the command), it installs the current package context (ie, the current working directory) as a global package.
How to create custom NPM modules?
Creating a private package. If you are using npmrc to manage accounts on multiple registries, on the command line, switch to the appropriate profile: npmrc. On the command line, create a directory for your package: mkdir my-test-package. Navigate to the root directory of your package: cd my-test-package.
What Is npm and Why Is It Important?
What Is A Package Manager?
- Consider the scenario in which you include library A in order to personalize a text field.
- The text in that library is formatted by library B, and the translations are shown by library C.
- Consider the following scenario: library C utilizes another five separate libraries to handle multiple languages at the same time, resulting in a system similar to this one.
- The dependency tree of your program is what this is referred to as.
- Your project will eventually become entangled in a web of dependencies, many of which you will not even be aware of at the time.
- And, to make matters worse, each of those dependencies will only be compatible with a certain version of each of those dependencies.
Manually navigating through this circumstance would be a nightmare.A minor change in a submodule might cause your dependency tree to become unusable, and your app could fail to compile.That is exactly the problem that npm is designed to fix.
When you build a npm library, a json file named package.json is generated, in which you may indicate which dependencies your JS library requires.At the same time, each of your library’s dependencies will have its own package.json files, resulting in the creation of a complete dependency tree.
If someone wishes to include your library in their project, they will only need to perform the following commands: npm install is a command-line tool that allows you to install Node.js modules.All of the requirements for the tree will be obtained and installed in a magical manner.Due to the fact that you don’t have to worry about the dependencies in practice, this solution is quite remarkable.
Is There Any Downside of Using a Package Manager?
- In particular, developers lose control over which code is included in their projects, which is the most serious issue.
- Security concerns have occurred in the past, and essential systems require a dependency tree that is well regulated and adheres to stringent rules.
- Let us consider the following scenario: a freshly established project in React Native contains more than 1500 dependencies.
- It seems improbable that more than a few people are familiar with all of them.
- If someone injected dangerous code – or simply a flaw – into the system, a large number of developers would almost certainly accept that code without even realizing it.
- Don’t be concerned.
This is an extremely uncommon event.However, it has already occurred on a few of occasions.Another example is the argument that erupted in 2019 between an open-source developer and an American firm, which came close to bringing the internet down completely.
A long story short, a developer made the decision to remove a simple but often used library from the Node.js package manager (npm), causing the dependency tree of thousands of projects all over the globe to become unusable.
Why Should You Create Your Own npm Package Libraries?
- The quickest and most secure method of developing code is to refrain from writing it.
- So, the next time you need to utilize those features, you won’t have to copy and paste or build them from scratch — you can just refer to your library instead.
- Furthermore, if you discover a flaw, you may repair it once and then disseminate the remedy to the rest of your projects at the same time.
- Once you’ve developed your node module, one of the quickest and most convenient methods to incorporate it in your projects is to use the npm package manager.
- That’s exactly what we had in mind when we created the remote logger BugfenderJS in the first place.
Even while our SDK may be included manually, the vast majority of our users just install it using npm: install.$ npm install @bugfender/sdk $ npm install @bugfender/sdk
Creating Your Own npm Package
1. Create a New Git Repository
If you’ve already written some code, you may go on to the next section. If you are starting from scratch, on the other hand, it is necessary to run git init. Once you’ve done that, you can go to Github and create a new git repository.
2. Create your package file
- Now, open the terminal and browse to your project with the command $ cd folder/to/your project. And then enter $ npm init to get started. This tool will guide you through the process of creating a new package. JSON is asking you for the most fundamental information it need. Here are a few pointers: Package name: keep in mind that the npm community prefers that you use kebab-case for your package names
- While it is recommended that you begin your project with version 1.0.0, if you are just getting started, it is usually best to start with something like 0.0.1 and upgrade to 1.0.0 once the code has been well tested. Additionally, other developers who use your library will enjoy the fact that your versioning accurately represents the current state of your code.
- Straightforward and simple to comprehend
- This is the file that serves as the entry point for your library. It is the file that other developers who wish to use your library will be required to create when including it using the reguire(‘your-package’) command line option. If you’re simply utilizing one file, index.js will enough for your needs. Nevertheless, if your project is likely to have more files, it is preferable that you use src/index.js.
The remaining fields can be skipped if you don’t want to fill them out right now and come back later to include them in the package. json formatted file
The majority of the time, you have some code that you have been copy-pasting across several projects and you want to move it to a npm module so that you may reuse it in the future. If this is the case, it is now necessary to include this code in the npm project. After that, you’ll need to think about the API that you’ll be exposing to the rest of the world.
Define Your Public API With module.exports
- The module.exports object, which should be included in the entry point of your library, is the means through which you inform npm about the features that your library is providing (usually the index.js).
- In the module.exports variable, you may provide whatever you wish.
- It might be a number, a function, a class, or anything else.
- Assume that you are constructing the module from the preceding sample bugfender-coffee-machine module.
- When a user types: const coffeMachine = require(‘bugfender-coffee-machine’); the following code is generated: Then, your code will navigate to the index.js file and determine the value of the specified module.
- For example, if you put the following value in your index.js: module.exports = 42; then coffeMachine will be a number with the value 42.
The following would be a more practical approach: assign this value to an instance of a class.bugfendercoffeemachine is a module exported by the index.js file./ Using the following code in your app: const CoffeeMachine = require(‘bugfender-coffee-machine’); const coffeeMachine = new CoffeeMachine(); coffeeMachine is now an instance of BugfenderCoffeeMachine, and you can perform the following operations on it: coffeeMachine.prepareCoffee()
Add a README.md File
- The simplest and most little step is actually one of the most critical.
- A well-written Readme file guarantees that other people will be able to grasp what your library is about – and how to use it – when they come across it.
- It is not necessary to be very imaginative; simply pick a template such as this one and make an effort to fill out all of the fields in an orderly manner.
- You will be appreciated by the users of your npm package since you have saved them time.
- Even a future version of yourself will appreciate having clean documents!
Now that your library is complete, you may move to the next step: committing your first change. There are already a plethora of documentation on how to make relevant git commits, just like there is for the Readme file.
4. Publish on npm
Sign up to npm
- If you don’t already have a npm account, now is the time to create one.
- npm is a command-line program that simplifies the development process.
- Open the terminal and type the following: $ npm login You will be asked for your email address and password.
- You may verify that you are logged in successfully by running the command $ npm whoami.
- A helpful hint: before you publish a new Node.js package, make sure that you are signed in as the appropriate user.
- For those who use the same PC for both professional and personal pursuits, this is especially important to remember.
Test Your Framework
- We are on the verge of releasing our first book.
- But, just to be sure, we can conduct a fast test on our local machine.
- To begin, browse to the location of your library file path, which is the same location where you saved your package.json, and run the command npm link.
- route-to-your-library/ $ npm link cd./route-to-your-library/ As a result, the project gets added to your local npm registry.
- This time, specify the name of the package that you specified in the npm init step.
- It’s time to share your library with the rest of the world now that you’ve finished developing it and testing it locally.
- The following command will redirect you to your library: $ npm route your library publish npm will begin work on publishing your library to the official repository, which will take some time.
- Following completion, the library should be available in and every person on the planet should be able to install it using the npm installation command.
5. Updating your library
- Despite the fact that we’ve reached the conclusion of the article, we’re only at the beginning of your library’s journey.
- If you begin to use it and other people begin to use it, you will be responsible for keeping it up to date.
- It will be necessary to incorporate new features or replace deprecated code from time to time in your application.
- Always remember to utilize Semantic Versioning if you do something like this (major.minor.patch).
- With the npm versioning tools, npm makes the process of maintaining your code much simpler: $ npm version patch $ npm version patch Starting at 0.0.1 and progressing until 0.0.2 $ npm version minor npm version minor From 0.1.0 to 0.2.0, there is a significant increase in performance.
- $ npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major npm version major n From version 1.0.0 to version 2.0.0 Keep in mind that the npm version command updates the package.
json, generates a commit, and adds a TAG to the git repository.
One Last Thing
- We at Bugfender are software engineers ourselves, therefore we understand the importance of these resources.
- We appreciate you taking the time to read this post and hope that you will assist us by sharing it with your colleagues.
- Bugfender is a remote console logger that was designed for developers, by developers.
- It is free to use.
- You can join up for a free account in less than 20 seconds, and you can integrate the SDK into your website in an extra 10 seconds by running npm install @bugfender/sdk from your terminal (not bad for half a minute;-).
Tutorials and troubleshooting tales are published on a regular basis on our blog.Do not forget to return to our site on a regular basis, or better yet, subscribe to our quarterly spam-free newsletter to receive an overview of the most recent articles.
Creating your first npm package
- This past weekend, I began working on my very first Node.js package (npm package).
- I can’t believe that for all of the years I’ve been writing code, I’ve never thought of creating my own Node.js package, but here we are.
- Gridsome and markdown were used in the development of my most recent website, which you can read about here.
- To make it simple to input a twitter status and embed the tweet in the markdown files, I created a template.
- This Gridsome plugin will be covered in greater detail in a later blog post, but for now, I’d want to demonstrate how to create your very first npm package using the NodeJS package manager.
- While working on this project, I picked up a few valuable lessons that I’d want to share with you.
- Node & NPM
- an NPM account
Creating your npm package
Writing your plugin
npm local development
Publish Source Code
Publishing NPM Package
- I know that some people believe that you should generate documentation from the beginning of your project, but I am not always sure what my code will look like in the end, so I normally wait till the end. Create a README.md file in the root directory of your project and fill it with information about your project’s requirements. Was there a reason for creating your npm package? How do I install it? Are there any configuration options?
- Despite the fact that I uploaded my first Node.js package this weekend, as I mentioned at the outset, I can’t believe it.
- I’d just never really had a reason to do so until now, so I was surprised and delighted to discover how simple it was.
- If this is your first time creating a npm package, please leave me some feedback or let me know through Twitter when yours is complete!
- Good luck with your coding!
- Dan This story was originally published on my personal blog at If you like this post, please consider subscribing to my email or following me on Twitter to stay up to date.
A step-by-step guide on how to use npm to host your library so you can share it with the world.
- The more I learn about designing and growing my own applications, the more I find myself relying on npm packages to help me along the way. To now, there are more than a million parcels, and the number is growing. Some packages receive millions of downloads each week, while others receive only a few thousand. Some are complicated, while others are relatively straightforward. As a creative person who enjoys creating, I couldn’t help but be perplexed. What is the best way to create my own npm package? If you’ve been wondering about the same question, I’ve got the solutions for you! In this blog post, I’ll walk you through the process of creating your own Node.js library from scratch using the npm package manager. The basic library that I’m going to use as an example is one that capitalizes the initial letter of every word in a given phrase. Before you begin, make sure you have the following items ready: An account on GitHub
- An account with npm
- Check to see that Node.js and npm are installed on your computer.
- We can get started on creating and releasing your npm package as soon as you have your accounts set up and everything installed on your computer. If you are as particular as I am, this may prove to be one of the most difficult phases for you to complete. Also, just when you think you’ve come up with the finest conceivable name, it might already be stolen by someone else. Before getting too attached to a name, you can check to see if the name you want is already taken on the npm website, or you can use this website to enter the name you want and it will tell you if it is already taken:It is critical that your package name is unique, especially if you plan on publishing it as a public package on the internet. The name of the package we are going to develop is first-letter-case-converter, and I’m going to use it as an example in this section. Create a new repository on GitHub for your npm package and add it to your project. This example would have a repository name that starts with the letter ″F″ and ends with ″C.″ Make certain that it is correctly initialized with a README. It is also possible that you may wish to select an appropriate license for the repository. This is especially important if you intend to make your npm package available for other developers to utilize. The MIT license is one of the most generally used, but you may do your own study to pick the one that works best for you. For more information on licensing a repository, see the GitHub documentation. Make a note of your name, email address, and website in npm. When the project is formed, these details will be included in the package.json file, which will be put to the root of the project’s directory. npm set init.author.name ″″npm set init.author.email ″npm set init.author.url ″″npm set init.author.url ″″npm set init.author.email ″npm set init.author.url ″″npm set init.author.email ″npm set init.author.url ″″ After that, use the command npm login to log into the npm package manager. After that, you will be prompted to provide the credentials that you used to create the npm account. In order to get started, create a new directory for the project and run the npm init command to get it started. Make sure you complete out all of the fields shown below: Name of the package, version, description, Git repository, keywords, and license.
- (base) first-letter-case-converter (first-letter-case-converter) npm init is a command that starts the npm package manager. This tool will guide you through the process of generating a package.json file. It only covers the most popular things, and it makes an attempt to assume reasonable default values. For authoritative documentation on these fields and exactly what they do, type ‘npm help init’ into your terminal. After that, run ‘npm install’ to install a package and store it as a dependency in the package you’re working on. json formatted file To exit the game, use the C key at any point. package name: (first-letter-case-converter)version: (first-letter-case-converter) (1.0.0) description: The initial letter of every word in a sentence is converted to a capital letter using this function. jQuery entry point: (index.js) jQuery app.jstest command: mochagit repository: capitalize, converter, case, johnsmith is the author of the letter Licensing information: (ISC) MIT In the process of creating a package.json file with the following attributes:,″repository″:,″keywords″:,″author″: ″johnsmith″, ″license″: ″MIT″, ″bugs″, and ″homepage″, the following information is being written: ″ Is this all right? (yes) yes (base) first-letter-case-converter (first-letter-case-converter) All of these fields will be included in the final bundle as well. json formatted file You may optionally include an additional field in the package called ″engines.″ The following json file should be used to identify the newest version of Node.js with which your package is compatible: ″engines″:, If you publish a package to npm, the default version for that package should be 1.0.0, so you won’t have to worry about it right immediately. That being said, you should be informed of how to update the version ahead of time so that when the time comes to update your package, you can be confident that you are doing it effectively and efficiently. As your public package is installed, downloaded, and used by developers all over the globe, and as the technology you are using matures and grows, you may wish to update your npm package to reflect these changes. When you make an update to your package, you will also need to make an update to the version. Npm makes use of a versioning mechanism known as Semantic Versioning (SemVer), and as previously stated, the default beginning version is 1.0.0 of the package. There are three sorts of version adjustments you may make to your package in order to prepare it for future upgrades in accordance with Semantic Versioning guidelines. Major, minor, and patch version changes are the three categories of version updates: When you make significant modifications to your package, this is referred to as a major version. API modifications that are incompatible with one another are an example.
- When you add feature in a way that is backwards compatible, this is known as a minor version.
- When you make bug fixes that are backwards compatible, you create a patch version.
- Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format, which can be used in conjunction with other formats. More information on Semantic Versioning may be found here. The following step is to put your package into action. In this example, I’m going to show you how to use the first-letter-case-converter package. In app.js, or whichever file you choose to serve as your entry point, you would include the code that pertains to the package you are creating. The following is the code that I inserted in app.js for the first-letter-case-converter package: Let converted = capitalized be the result of the function converter(sentence)). return convertedmodule.exports = converter
- join(″ ″)return converted I made use of a straightforward function named converter. It receives a statement as a string and capitalizes the initial letter of each word that appears in the sentence. The most significant element of the code above is the use of module.exports to export the function that was defined before. Following that, you must initialize git for your project/package by running the following command: git init is an abbreviation for Git Initialization Protocol. Then, using the command:git add, stage the files that you’ve made changes to. Afterwards, commit the code changes you’ve made to your local repository as follows: git commit -m ″initial changes″ git commit -m ″initial changes″ Then, as the project’s remote repository, specify the following information: git remote add origin (git remote add origin) Then, after pulling the changes from the remote repository, push the modifications from the local repository to the remote repository. git pull origin master is a command that pulls the origin master from git. git push origin master git push origin master This may appear to be a random or pointless task, but it is really quite crucial to complete. I’m curious how many times you’ve installed a npm package and then had to go online or look at samples of code to find out what it does. Writing an effective README for your package may make a significant difference in its success and widespread use. It provides consumers and potential users of your package with a high-level overview of what it does and how they can incorporate it into their projects. To get a better understanding of what a decent README for a npm package looks like, you can have a look at some popular npm packages and their GitHub repositories. In general, the following should be included in your README: a description of your package and what it is intended to do
- The process through which other users may install the package so that they can utilize it in their project
- How to incorporate the package into your project. Provide code examples that demonstrate how to use the code. This is very crucial to note
- What other people can do to help you with your package. If you anticipate that additional developers may contribute to this project, make sure to provide this information in your README.
- The license that is being utilized by the package
- This will be the quickest and most straightforward process.
- Simply enter the following code into your command-line to complete the process: npm publish is a command that allows you to publish a document.
- If you picked a unique package name (i.e., one that does not already exist), your package will be uploaded to the npm repository!
- Create a new project and include your new package as a dependency in that project’s code.
- In the next section, I will walk you through the installation of my first letter-case converter package: npm install first-letter-case-converter -save install first-letter-case-converter -save This will allow you to easily add a package to your new project and customize it to your specifications.
- As an illustration, the following statement is created by utilizing a package that capitalizes the initial letter of every word in the sentence: const converter = must be used (″first-letter-case-converter″) allow convertedSentence to equal converter; (″i love to learn new things″) / This will result in the statement: ″I Enjoy Learning New Things.″ However, as you become more familiar with the process of generating npm packages, you may make them as sophisticated or as simple as you see appropriate.
Ultimately, if you understand the process and have tried it, creating and distributing a npm package is pretty straightforward.You now understand what it takes to develop your own npm package and make it available for download.Thank you for your time and consideration.
Please feel free to share any npm packages you make with me.More information may be found at plainenglish.io.
A Step-by-Step Guide to Create and Publish npm Package
- In this article, you will learn how to develop your own Node.js package and submit it to the Node.js repository. You will get an understanding of the following: How to create a npm package using node.js
- How to test its operation by installing it locally first before distributing it
- Instructions on how to install and utilize the published package using either the ES6 import syntax or the Node.js require statement.
- In this section, we will discuss how to handle the package’s semantic versioning.
- Methods for updating the package to reflect the new version and re-publishing it
For further detail, you will create a package that returns a list of GitHub repositories belonging to the supplied username, arranged according to the amount of stars each repository has received.
- To complete this lesson, you will require the following materials: A working installation of Git version control
- Node.js installed locally, which you may accomplish by following the instructions on this page
- and a working installation of Git version control.
Step 1 — Initial Setup
- Start by creating a new folder with the name github-repos-search and then initializing a package in that folder.
- Make a directory for the json file: mkdir github-repos-search cd github-repos-search use npm init -y to start a new project The following command should be used to set up the current project as a git repository.
- It should be executed from the github-repos-search folder: Start with git init.
- Create a.gitignore file to prevent the node modules folder from being included in your project.
- Insert the following material inside the container.
- node modules is a gitignore file.
Install the axios package, which will be used to make a request to the GitHub API in the next step.npm install axios is a command-line program that installs axios.Your package.json file will now look something like this: Make sure to take a look at our newest offering, the ultimate tailwindcss page maker!
The ″name″ of the project is ″github-repos-search″, the ″version″ is ″1.0.0″, the ″description is ″″, the ″main″ is called ″index.js″, the ″dependencies″ are ″axios″: ″0.20.0″, the ″devDependencies″ are ″axios″ and ″devDependencies are ″scripts″: ″test″: ″echo ″Error: no test specified″ && exit 1 The name github-repos-search is defined in the package.json file, which is located at the root of the package directory.As a result, after publishing to the npm repository, the package name will be changed to github-repos-search.Also, the name must be unique on the npm repository, so first determine whether or not such a npm repository already exists by visiting to the npm repository page.
If the package name already exists in the npm repository, you will receive an error while attempting to publish the package to the npm repository.
Step 2 — Writing the code
- Creating a new file with the name index.js and pasting the following contents into it will result in the following output: const axios = require(‘axios’)
- const getRepos = async (username =’myogeshchavan97′, page = 1, per page = 30 =>) => => try const repos = await axios.get(‘)
- return repos.data.map((repo) => try const repos = await axios.get(‘)
- return repos.data.map((repo) name: repo.name, url: repo.html url, description: repo.description, stars: repo.stargazers count
- ) return sort((first, second) => second.stars – first.stars)
- sort((first, second) => second.stars – first.stars)
- catch (error) return
- getRepos().then((repositories) => console.log(repositories))
- getRepos().then((repositories) => console.log(repositories))
- getRepos().then((repositories) => console.log(repositories))
- First, let’s get a better understanding of the code. You’ve written a getRepos method that receives an optional object with attributes for the user, the page, and the per page parameter.
- After that, you utilized object destructuring syntax to extract the properties of the object from the object.
- Given that passing an object into the method is entirely optional, we have initialized it to default values in the event that the object is not supplied into the function as follows.
- This is done to avoid receiving an error while destructuring username from the object if the object is not given. = username =’myogeshchavan97′, page = 1, per page = 30
- Within the method, you are using the GitHub API with the appropriate arguments, which returns the repositories of the specified user, sorted by the date they were last modified.
- Awaiting axios is same to waiting for const repos. get(‘)
- We are employing the async/await syntax in this case, and the getRepos method is defined as async.
- The Array map method is then used to choose only the required fields from the answer
- this is called selective selection.
Repos.data.map((repo) => Repos.data.map((repo) name: repo.name, url: repo.html url, description: repo.description, stars: repo.stargazers count;) return That result is then sorted in decreasing order of stars, with the first piece in the list having the most stars, and so on and so forth.
- .sort((first, second) => second.stars – first.stars)
- .sort((first, second) => second.stars
- The catch block returns an empty array if there is an error
- otherwise, the catch block returns an empty array.
- Because the getRepos method is specified as async, you will receive a promise in response
- thus, you are using the.then handler to obtain the outcome of the getRepos function call and publishing it to the console
Once ((repositories) => console.log(repositories)), GetRepos().then((repositories) => console.log(repositories));
Step 3 — Executing the code
- Now, from the command line, launch the index.js file by entering the following command: index.js The node index.js file is included.
- You will see a list of the first 30 repositories, which are as follows: Given that you haven’t specified a username in the file, my repositories are displayed by default by default.
- Let’s make the following update to the code in the example: getRepos(username: ‘gaearon’).then((repositories) => console.log(repositories)); getRepos(username: ‘gaearon’).then((repositories) => console.log(repositories); Once more, run the file by performing the node index.js command, and you should see the following output: Alternatively, you may pass in the page and per page attributes in order to alter the answer so that you only get the top 50 repositories.
- getRepos(‘gaearon’ as the username, page: 1, per page: 50 as the per page value).
- then((repositories) => console.log(repositories)); then((repositories) => console.log(repositories)); You now have confirmation that the functionality is operational.
- Exporting this module will allow you to call the getRepos function from any other file in the future.
As a result, the following code should be removed from the file: getRepos(‘gaearon’, page: 1, per page: 50 ‘).then((repositories) => console.log(repositories)); and replace it with the following code instead: getRepos(‘gaearon’, page: 1, per page: 50 ‘).then((repositories) => console.log(repositories)); module.exports =; module.exports =; You are exporting the getRepos function as a property of the object in this case, so that if you wish to export any other function in the future, you can easily add it to the object as a property of the object.As a result, the preceding line is the same as the following line: module.exports =; module.exports =;
Step 4 — Testing the created npm package using require statement
- You have completed the creation of the npm package, but before publishing it to the npm repository, you must test it to ensure that it functions properly when invoked via the need or import statements.
- There is a quick and simple technique to determine this.
- From within the github-repos-search folder, run the following command from the command line: github repos search npm link (npm link) When you use the npm link command, a symbolic link is created between your current package and the global npm node modules folder (The same folder where our global npm dependencies get installed).
- As a result, you may use the npm package you just built in any project.
- In order to verify that the package has been correctly installed, create a new folder on your desktop with whatever name you choose, for example test-repos-library-node, and populate a package.json file with the following contents: make test-repos-library-node in the directory /Desktop testing the repository library node (cd test-repos-library-node) use npm init -y to start a new project If you recall, the name property in our package’s package.json file was github-repos-search; thus, you must need the package with the same name as the property in our package.json file.
- After that, from within the test-repos-library-node folder, run the following command to make use of the package you just created: npm link (npm link) github-repos-search Creating a new file with the name index.js and pasting the following code into it will get the desired result: getRepos = require(‘github-repos-search’); const = require(‘github-repos-search’); ().
then((repositories) => console.log(repositories)); then((repositories) => console.log(repositories)); This is an example of how to import a package straight from the node modules folder (This was only possible because you linked it using the npm link).Now, run the file by entering the following command into the command line: node index.js This is what you will see when you run the program correctly: This demonstrates that when you publish a npm package on the npm repository, anybody may use it by installing it and executing the need statement on the command line.
Step 5 — Testing the created npm package using the import statement
- By utilizing the need statement, you have confirmed that the package is functional.
- Let’s check it out with the help of the ES6 import statement.
- The following command, which should be executed from your desktop folder, will create a new React project: file:/Desktop/npx/cd npx/ test-repos-library-react-create-react-app-test-repos-library-react Now, from within the test-repos-library-react folder, run the following command to make the package you just made available for use: Nodejs link github-repos-search Node.js link Now, open the src/App.js file and replace the following content with the one that follows: The following imports are made: import github-repos-search; import React, from’react’; function App() => useEffect((); import React, from’react’; ((repositories) => console.log(repositories)); return (); getRepos().then((repositories) => console.log(repositories)); return ();
Open browser console to see the output.
- ); export the default application; Begin by issuing the following command from the terminal to launch the React application: start of the yarn Now, If you look at the output in the browser console, you will find that it is as expected: This demonstrates that when you publish a npm package to the npm repository, anybody may use it by installing it and executing the import statement on the package.json file.
Step 6 — Publish to the npm repository
- You have now successfully confirmed that the package is operational.
- It’s time to make it available in the npm repository.
- Return to the github-repos-search project folder, where you previously generated the npm package, and save your work.
- Let’s add some metadata to the package to make it more useful.
- The package’s json file is used to display more information about the product.
- The completed bundle is shown below.
The json file is as follows: ″The name of the project is ″github-repos-search″, the version is ″1.0.0″, the description is ″″, the main file is called index.js, and the home page is called homepage.js.The repository’s type is ″git″, the url is ″git+″, the dependencies are ″axios0.20.0″ and ″devDependencies″ are ″axios0.20.0″, and the scripts are called test and echo.The scripts are called test and echo.
[″github″, ″repos″, ″repositories″, ″sort,″ ″stars,″ ″author,″ ″license,″ and ″keywords″]; ″author,″ ″Yogesh Chavan,″ ″license,″ and ″keywords″: [″github″, ″repos″, ″repositories″, ″sort,″ and ″stars″]; and ″keywords″ and ″keywords″ and ″keywords″ and ″keywords and stars.″ ″ For further information, you have included the homepage, repository, keywords, and author (These are optional).Make the necessary adjustments in accordance with your GitHub repository.To use this URL, create a new GitHub repository, and then push the github-repos-search repository to the GitHub server.
If you don’t already have an account, go to and register for a new one.Open a terminal window and, from within the github-repos-search folder, type the following command into the terminal: To log in, navigate to npm login and input your npmjs website credentials.After that, execute the following command in order to get it published to the npm repository: npm publish is a command that allows you to publish a document.If you navigate to the following address in the browser, you will see your recently published package: Now, let’s add a readme.md file to the package, which will provide some information about the package.Create a new file with the name readme.md within the github-repos-search folder and paste the text of this page into it.
- github-repos-search is a subdirectory of github.
- Let’s try publishing it once more with the npm publish command this time.
- You will receive the above-mentioned error.
- This is due to the fact that you are republishing the module with the same version as before.
- If you look at our package.json file, you’ll notice that the version number in the file is 1.0.0, which is correct.
- You must increment it each time you publish a new version of the document.
- So, what should you make the next increase to?
- You must first grasp the notion of semantic versioning in order to accomplish this.
Step 7 — Semantic versioning in npm
- Using the dot operator to separate the three numbers, the version value can be calculated.
- So let’s pretend that the version number is a,b,c.
- The first value (a in a.b.c) defines the major version of the package — This signifies that this version has significant code changes and may contain API modifications that are potentially dangerous.
- The second number (b in a.b.c) denotes the minor version, which contains only minor modifications and will not include any API changes that are considered to be breaking.
- The third number (c in a.b.c) provides the patch version, which is generally the most recent one and contains all of the problem fixes.
- Because you only inserted a readme.md file and did not make any API changes, you may increase the patch version by one number, which is the last digit in our example.
As a result, alter the version number within the package.Change the version number of the json file from 1.0.0 to 1.0.1 and rerun the npm publish command.If you go to the npm package page right now, you will notice that the revised npm package is available.
The npm package you generated in this lesson was submitted to the npm repository, and you earned a certificate for your efforts. Check out the github-repos-search repository on GitHub if you want to see the whole source code from this lesson. You can also view the published npm module by visiting this page.
Thanks for reading!
- Check out my freshly released Mastering Redux course for more information. In this course, you will learn: Redux fundamentals and advanced concepts
- Learn how to deal with the complicated state of an array and its items.
- Using numerous reducers to manage complicated redux state is explained in detail.
- What is the best way to debug the Redux application?
- How to utilize Redux in React, and how to use the react-redux package to make your project more responsive
- This tutorial will teach you how to utilize the redux-thunk libra