NPM (Node Package Manager)
is a tool to create and manage Javascript programming libraries for Node.js. Developers develop NPM packages and publish them to NPM’s server for use and sharing with the community. You often use the command npm install <packageName>
to install libraries from NPM, right? Have you ever wondered if you can write your own packages to reuse, share with colleagues and contribute to the developer community? In this article, I will share with you the steps to publish a javascript package with NPM.
(Note: The knowledge you should have before refer to the article information: Install and use NPM (basic), GIT knowledge (basic), Javascript knowledge (basic). is the premise for you to easily access the content presented next).
Step 1: Set up an NPM account
Sign up for an npm account here . This is where we will push packages and manage them.
Step 2: Create Repository git
Create repository at github . Your package needs to be in a pulic repository. This will be the page to help us manage the source code and documentation for the package.
Step 3: Create folder package
You need to create a directory that is the name of the package you want to write. The structure inside the directory of a package is very simple with the following 2 files:
- json: declare information about package
- js: write in a module structure, export components. When require package is to perform require this file.
Step 4: Create the package
For everyone to understand quickly, here we will try to make a simple package about random troops in the game Empire (AOE). I chose this example because the number of people who know this game is quite large. You can preview the demo and source code here:
4.1. Create file package.json
First we create directory aoerandom
and file package.json
to store configuration information of the package. Quick initialization with the command npm init -y
, we immediately have the file package.json
with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{ "name": "aoerandom", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC" } |
- Name: is the name of the package you want to set. By default it is taking the name of the directory containing the package.json . file
- Version: the name of the current version of the package. Default is 1.0.0
- Description: information, introduction to the package
- Main: that is the file written in the export structure. Default is index.js. When you require package, you require this file
- Scripts: defines the local commands of the package
- Keywords: keywords related to the package, making it easy to find your package. Keyword will help more people know about your package.
- License: the license of the package.
With this package, my structure will be as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
{ "name": "aoerandom", "version": "1.0.0", "description": "Hỗ trợ game thủ random quân, tạo kèo đấu trong game AOE", "main": "index.js", "homepage": "https://github.com/FightLightDiamond/aoerandom", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [ "AOE", "GAME", "RANDOM", "JS", "Age of Empires", "CUONGPM", "FightLightDiamond" ], "author": "FightLightDiamond", "license": "ISC" } |
The main homepage
is the github
link of the package.
4.2 Contents of the program
Next, I create an index.js file with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
// Các loại quân trong AOE const items = [ 'Egyptian', 'Greek', 'Babylonian', 'Assyrian', 'Minoan', 'Hittite', 'Phoenician', 'Sumerian', 'Persian', 'Shang', 'Yamato', 'Choson', 'Carthaginian', 'Palmyran', 'Macedonia', ]; // Lấy ngẫu nhiên một loại quân getCountryRandom = () => { const randomIndex = Math.floor(Math.random() * items.length); return items[randomIndex]; } // Random cho một Team.getTeamRandom = (length) => { let countries = []; for (let i = 1; i <= length; i++) { const item = getCountryRandom() countries.push(item) } return countries;} exports.getCountryRandom = getCountryRandom exports.getTeamRandom = getTeamRandom |
Pretty easy to understand example, right? And with the input data are the types of troops in the game. We have the following two functions:
- getCountryRandom: Issue a random piece. Used in solo play, one person will randomize first, then the next person will automatically choose counters. For example: A: Greek, then B: choose Egyptian.
- getTeamRandom: Randomize depending on the number of players. Use in team play.
4.3. Install Packages globally (command)
When installing a global package with the -g parameter, we will use the package’s commands:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
aoerandom <số người chơi> ``` Tiếp theo, cùng tạo thư mục commands (thư mục danh riêng cho file command), tạo file command aoerandom.jsvới nội dung như sau: ``` #!/usr/bin/env node // require để sử dụng hàm random đã được viết const aoe = require('../index.js') // hàm radom random = (num) => { num = parseInt(num); console.log('You want random team size is ' + num) if(num > 8 || num <1 || num === undefined || isNaN(num)) { console.log("Số game thủ của game từ 1 đến 8. Bạn vui lòng thử lại!") return } for (let i = 1; i <= num; i++) { const item = aoe.getCountryRandom() console.log(i, item); } } // lấy parameter const argvs = process.argv // Từ index số 2 là tham số chúng ta truyền vào, ở đây là số người chơi. random(argvs[2]) |
In order for NPM to understand the command, we need to continue declaring it with package.json as follows
1 2 3 4 5 6 |
"bin": { "aoerandom": "commands/aoerandom.js" }, |
Detail:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
{ "name": "aoerandom", "version": "1.0.0", "description": "Hỗ trợ game thủ random quân, tạo kèo đấu trong game AOE", "main": "index.js", "homepage": "https://github.com/FightLightDiamond/aoerandom", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "bin": { "aoerandom": "commands/aoerandom.js" }, "keywords": [ "AOE", "GAME", "RANDOM", "JS", "Age of Empires", "CUONGPM", "FightLightDiamond" ], "author": "FightLightDiamond", "license": "ISC" } |
4.4. Testing locally before publishing
Before publishing the package, test it out by publishing it locally with the command npm link
.
The result from the command returns:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN aoerandom@1.0.0 No description npm WARN aoerandom@1.0.0 No repository field. up to date in 1.002s found 0 vulnerabilities /usr/local/bin/aoerandom -> /usr/local/lib/node_modules/aoerandom/commands/aoerandom /usr/local/lib/node_modules/aoerandom -> /Users/adminadmin/ad/Repositories/api/aoerandom |
Next, we test random troops for 1 match 4-4 corresponding to 8 players
1 2 |
aoerandom 8 |
Results returned:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
1 'Macedonia' 2 'Phoenician' 3 'Persian' 4 'Egyptian' 5 'Carthaginian' 6 'Phoenician' 7 'Choson' 8 'Yamato' |
Pretty good cards for team 1, right? Let’s try it a second time and see.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
1 'Minoan' 2 'Macedonia' 3 'Carthaginian' 4 'Babylonian' 5 'Palmyran' 6 'Hittite' 7 'Egyptian' 8 'Shang' |
Conversely, if you want to remove it, simply with the command
1 2 |
npm unlink |
Step 5: Publish package to NPM
First, you will need to login to npm.
1 2 |
npm login |
Next, let’s push the package up to share with everyone. If this is your first time publishing a package on NPM, you will need to confirm with your registered email address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
npm publish npm notice npm notice 📦 aoerandom@1.0.0 npm notice === Tarball Contents === npm notice 383B commands/aoerandom.js npm notice 773B index.js npm notice 408B package.json npm notice 524B readme.md npm notice === Tarball Details === npm notice name: aoerandom npm notice version: 1.0.0 npm notice package size: 1.2 kB npm notice unpacked size: 2.1 kB npm notice shasum: d13d1c06b6c0c740d2b86cd42784ca245fa4468a npm notice integrity: sha512-XvzLz0J2q2Hgv[...]7h+XxvdZ2JL3g== npm notice total files: 4 npm notice + aoerandom@1.0.0 |
So you have successfully published the package. Now, try to visit npm’s website again to check if your package has appeared or not. Package when published will look like this: LINK
Step 6: Using package
Now we can use the package we just made to generate a random AOE page. The settings to use are as follows:
1 2 3 4 5 6 7 8 |
// cài đặt local npm i -S aoerandom // cài đặt global để sử dụng command npm i -g aoerandom |
You can use the package now
1 2 3 4 5 6 7 8 9 10 |
// ES5 const aoerandom = require('aoerandom') // ES6 import aoerandom from 'aoerandom'; import {getCountryRandom, getTeamRandom} from 'aoerandom'; |
We see that writing and publishing a package with NPM is fast and simple, right? As a programmer, surely everyone has a lot of favorite source code to share, so why not create a package with your own stamp today?
Some useful links:
- Packages published
- Quick Demo
- Reference: NPM document