Let’s create a JavaScript package to fetch a random GIF from Giphy API and publish it to npm. First, let’s create a directory for our package. Go to your terminal and run the following command to create a giphy-random directory:
# Make a new directory named giphy-randommkdir giphy-random
# Go to the created directorycd giphy-randomSet Up the Git Repository
Still within your package directory, let’s initialize a git repository:
git initUsing any of your favorite text editors, create a new file within your package directory named README.md. You can write about your JavaScript package there or just leave it empty for now. Let’s track that file with git and commit the change.
# Create an empty README filetouch README.md
# Track the README.md filegit add README.md
# Commit changes to the repositorygit commit -m "Initial commit"Let’s push our package to a remote repository. If you’re using Github, you can create a new repository here.
# Add a remote repository named origingit remote add origin git@github.com:risan/giphy-random.git
# Push the master branch to the remote origingit push --set-upstream origin masterSince it’s our first push to origin, we need to specify the --set-upstream flag. For the upcoming push, we can simply run:
git pushBuilding a package.json File
Run npm init and answer the questions:
npm initpackage name: (giphy-random)version: (1.0.0)description: A package to fetch a random GIF from Giphy APIentry point: (index.js) dist/index.jstest command:git repository: (https://github.com/risan/giphy-random.git)keywords: gif,giphy,funauthor: Risan Bagja Pradana <risanbagja@gmail.com> (https://risan.io)license: (ISC) MITThis is the generated package.json file:
{ "name": "giphy-random", "version": "1.0.0", "description": "A package to fetch a random GIF from Giphy API", "main": "dist/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/risan/giphy-random.git" }, "keywords": [ "gif", "giphy", "fun" ], "author": "Risan Bagja Pradana <risanbagja@gmail.com> (https://risan.io)", "license": "MIT", "bugs": { "url": "https://github.com/risan/giphy-random/issues" }, "homepage": "https://github.com/risan/giphy-random#readme"}Let’s commit and push it:
git add package.jsongit commit -m "Create package.json file"git pushPublishing
A few more tips for the rest of the process. To test the package locally within another project, use npm link. Use the prepublish script to build the package before it’s published, and use .npmignore to exclude the files that shouldn’t be published (here, the src directory). Finally, log in and publish the package.
npm link => test localy within other project
==============npm scripts:prepublish: npm run build
===============.npmignoresrc
===============npm addusernpm publish