Friday, October 14, 2022

Steps to follow to create and use a local npm module:

 Steps to follow to create and use a local npm module:


Create a directory
:

mkdir npm-test

Create a package.json file in the directory
:

cd npm-test
npm init

follow the steps at the prompt, keep the defalts, maybe add a description and author

If index.js is the entry point listed in package.json (by default, e.g "main":"index.js", create the index.js file:

touch index.js

Edit index.js with your favorite text editor. I am using vim. :

vim index.js

Add the following content within vim as a test :

exports.printMsg = function() {
     console.log("This is a message from the demo package.");

}

Create a package with the npm file
:

npm pack

unzip the tarball:

tar xzvf test-npm-1.0.0.tgz

In the unzipped package, link to the global package namespace:

cd package
npm link

Create a file folder to call the new npm package:

mkdir test-folder
cd test-folder

Make the npm package available:

npm link test-npm


Use the npm package in a test file:

touch testfile.ts
vim testfile.ts
add to vim: " import * as testy  from 'test-npm'
console.log(testy.printMsg) "
convert to js: tsc testfile.ts
run with node: node testfile.js

How to reverse the link:

Remove package in the test-folder:
      npm unlink --no-save npm-test

Remove global link to the npm package:
      cd npm-test/package/ 
      npm unlink

 
Sources:

https://docs.npmjs.com/cli/v6/commands/npm-pack

https://medium.com/@debshish.pal/publish-a-npm-package-locally-for-testing-9a00015eb9fd

https://www.cyberciti.biz/faq/unpack-tgz-linux-command-line/

https://medium.com/@alexishevia/the-magic-behind-npm-link-d94dcb3a81af








No comments:

Post a Comment