Tuesday, July 21, 2020

Test node js npm package in browser with parcel bundle

Usually node js app runs under node js environment, and testing a npm package within a console node app is inconvenient. It would be easier if npm package can be tested easily from browser as a web app.

Parcel bundle from https://parceljs.org/ can convert a node js app into a regular web app, so as to test and debug a npm package from browser. The below steps show how to test the npm package https://www.npmjs.com/package/financejs from browser.

1. run 
npm install -g parcel-bundler
to install parcel bundle

2. run
npm init
to initialize npm package file.

3. Add browserslist configuration in generated package.json to specify the allowed browsers
{
  "name": "npmtest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
"browserslist": [ "last 1 Edge version", "last 1 Chrome version", "last 1 Firefox version" ],
  "license": "ISC",
  "dependencies": {
    "financejs": "^4.1.0"
  }
}

 
4. create index.html with necessary ui element as below
<!-- index.html -->
<!DOCTYPE html>
<html>

<body>
    <input type="text" id="input"/>
    <button id="test">test</button>
    <p><b>Status:</b></p>
    <p id="status" style="height:160px; width: 593px; overflow: scroll;" />
  </body>

<script src="./index.js"></script>
</html>

5. create index.js using regular node js code as below. Basically, it imports financejs package, and then call CAGR method to get the required rate in order to double the amount in the specified years input by user.

const input = document.getElementById("input");
const testButton = document.getElementById("test");
const status = document.getElementById("status");

testButton.addEventListener("click", onclick);
const reportStatus = message => {
    status.innerHTML += `${message}<br/>`;
    status.scrollTop = status.scrollHeight;
}

var Finance = require('financejs');
var finance = new Finance();

function onclick() {
    var data = input.value;
    // To calculate Amortization
    let rate =  finance.CAGR(10000, 20000, data);
    reportStatus("rate is: " + rate);
}

6. From Windows command line tool or visual studio code terminal, run the below command to start the web app
parcel index.html
Based on the port number shows in console output, open browser to localhost:xxxx to debug the npm package from browser js debugger.

No comments:

Post a Comment