Using an NPM dependency in an HTML page - javascript

I'm currently working on a help and support form, and to make it easier to handle requests I need to retrieve some information about the user's connection (ping, upload, download). Until now we were redirecting our users to a website to do the test (https://www.speedtest.net/) but I found a dependency on NPM that allows to retrieve this information: https://www.npmjs.com/package/speedtest-net
I have never worked with NPM, and despite my research, my problem remains... The browser returns the same error every time : Uncaught ReferenceError: require is not defined (which I can understand, as require is not interpretable by the browser)...
For the moment here is where I am, I'm not even sure of what I started, if someone could help me to solve this problem, it would be very nice :D
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Speedtest - Test</title>
<script type="module" src="https://unpkg.com/speedtest-net#2.2.0/index.js"></script>
<script type="module" src="https://unpkg.com/speedtest-net#2.2.0/bin/index.js"></script>
</head>
<body>
<script>
(async () => {
try {
console.log(await speedTest());
} catch (err) {
console.log(err.message);
} finally {
process.exit(0);
}
})();
</script>
</body>
</html>

I suggest you to create a separated script where you can load your dependecias:
Create index.js
Run npm install --save speedtest-net
In your index.js set:
const speedTest = require('speedtest-net');
(async () => {
try {
console.log(await speedTest());
} catch (err) {
console.log(err.message);
} finally {
process.exit(0);
}
})();
Import index.js in your html file.

Related

How to use `request.js` by Octokit on browser?

I am a beginner with JavaScript. Even though I am directly running the examples on the readme, it doesn't work for me.
Here is a simple case where I try to get the number of my (user's) repositories.
I have the following html file (sans the api token) -
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script type="module">
import { request } from "https://cdn.pika.dev/#octokit/request";
</script>
<script>
const octokitRequest = require('#octokit/request');
myAsyncMethod()
async function myAsyncMethod () {
const result = await request("GET /users/:user/repos", {
headers: {
authorization: "token <your token>"
},
user: "armsp"
});
console.log(`${result.data.length} repos found.`);
}
</script>
</body>
ERROR
require.min.js:1 Uncaught Error: Module name "#octokit/request" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (require.min.js:1)
at Object.s [as require] (require.min.js:1)
at requirejs (require.min.js:1)
at github-api-test.html:11
github-api-test.html:1 Uncaught SyntaxError: The requested module '/universal-user-agent/^4.0.0/es2019/universal-user-agent.js' does not provide an export named 'default'
Then I tried to download the js file itself and include it in script tag the usual way, but I don't see any request.js file in src folder, all are .ts files. I don't know how to make sense of it.
Any help would be appreciated.
After talking with the authors of the library, it seems like it was an issue with a bad release. It has been fixed with version 5.3.1. The following example works now -
<script type="module">
import { request } from "https://cdn.pika.dev/#octokit/request";
myAsyncMethod();
async function myAsyncMethod() {
const result = await request("GET /");
console.log(result.data);
}
</script>
Live Demo here.

How to import modules for unit tests with QUnit

I've been trying to add unit tests for some modular ES6 code. I have a project structure like this:
project
└───src
| └───js
| cumsum.js
| index.js <--- entry point
└───test
tests.js <--- QUnit test code
This is what's in cumsum.js:
export const cumsum=x=>{
var result = x.reduce((r, a)=> {
if (r.length > 0) {
a += r[r.length - 1];
}
r.push(a);
return r;
}, []);
return result;
}
Now, if I run this sample test by running qunit in the command line, it will work:
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
assert.deepEqual([1,3,6,10,15],expected);
});
but if I try to import the actual cumsum function, it doesn't recognize proper ES6 import syntax:
import {cumsum} from '../src/js/cumsum';
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
assert.deepEqual(cumsum(A),expected);
});
I just get the error
SyntaxError: Unexpected token {
Is there a way to use QUnit with ES6 modules? If not, is there a unit testing framework that will let me test these modules?
Here's what I've come up with so far.
Chrome can sort of natively run ES6 modules. It's not good enough for web production but it is enough to run some unit tests. So in the test folder I have index.html like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>QUnit Example</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.9.2.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.9.2.js"></script>
<script type="module" src="../src/js/cumsum.js"></script>
<script type="module" src="tests.js"></script>
</body>
</html>
In test/tests.js I have the original test code:
import {cumsum} from '../src/js/cumsum';
const A=[1,2,3,4,5];
const expected=[1,3,6,10,15];
QUnit.test( "cumsum", function( assert ) {
assert.deepEqual(cumsum(A),expected);
});
Now, for some reason you can't directly open test/index.html in the web browser because although Chrome will happily read ordinary javascript files locally it will break if you set type="module" on a local file. Instead we have to launch a web server and view it that way. Any dev server will do, so webpack-dev-server works fine. Open http://localhost:8080/test/ in Chrome and the unit tests load.
Does anyone have a better way of doing this? Node.js uses the same javascript engine as Chrome so in theory I think it should be possible to do this from the command line without launching a web server and opening a browser.

Error Javascript ReferenceError: require is not defined in miIO Device Library

i try to use miIO library from https://github.com/aholstenson/miio but when i try use it i got error ReferenceError: require is not defined
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
const mio = require('./lib');
mio.device({ address: '192.168.31.148' })
.then(device => console.log('Connected to', device))
.catch(err => handleErrorHere);
</script>
</body>
</html>
can anyone help me to explain why this code got an error ?
The documentation you link to says:
miio is MIT-licensed and requires at least Node 6.6.0.
You are trying to run it in a web browser instead of in Node.
You need to run it in Node.
If you want to use require without nodejs then you'll need to use Browserify/RequireJS, as outlined in this question: How to use JS require() without Node.js

PouchDB too much recursion - Stackoverflow on remote connection

EIDT: This Problem is an Angular2 Problem and should be resolved with the next zone.js update. For a temporary fix see: https://github.com/angular/zone.js/issues/886 and Стефан Спасов Answer.
I'm trying to sync a client pouchDB with a server couchDB.
To access pouchDB from my Angular2 app I have written a javascript interface:
var db;
var remoteDb;
function LocalDb() {
db = new PouchDB('test', {storage:'persistent'});
};
function RemoteDb(url) {
remoteDb = new PouchDB(url);
};
function sync() {
db.sync(remoteDb);
};
function addTest() {
var test = {
title: 'ABC',
completed: false
};
db.post(test);
};
I removed all callbacks for readability. I installed pouchdb by running npm install pouchdb
I also added the pouchDB source by adding <script src="../node_modules/pouchdb/dist/pouchdb.min.js"></script> to index.html.
Because of the 404 Error i got by implementing it that way i copied the pouchDb dist folder into assets and implemented pouchDB that way <script src="assets/dist/pouchdb.min.js"></script>
All the javascript functions get called by buttons.
If i press the get localdb and the get remotedb button everythig works. At the moment i press the sync button I get a lot of wrapFn#http://localhost:4200/polyfills.bundle.js:3614:1 and a too much recursion error on firefox. Chrome tells me that the maximum call stack size exceeded.
Any help would be appreciated.
Edit... Ok now I'm completely confused... i got it working by creating a single static html file and running it in the browser with EXCACTLY the same script:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RemoteCouch</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<h3>Hello World</h3>
<script type="text/javascript" src="PATH/pouchdb.min.js"></script>
<script>
var db = new PouchDB('new');
db.post({
name: 'David',
age: 69
});
db.changes().on('change', function() {
console.log('Ch-Ch-Changes');
});
db.replicate.to('http://10.20.20.37:5984/new');
</script>
</body>
</html>
I hosted this file with the tapio/live-server and it works. This may be an Angular Problem, or i just did something wrong.
Just for one more try I made a new project, added pouchdb like described here https://github.com/nolanlawson/pouchdb-find/issues/201 and did the same tests in pure typescript but as excpected the error is still there.
I was having the same problem and apparently there it is an issue with zone.js. Should be resolved in the next version. For the time being using v.0.8.16 solves the problem for me.
"zone.js": "0.8.16"
Here is a reference to the github issue: https://github.com/angular/zone.js/issues/886

"ReferenceError: window is not defined" when compiling with r.js

I've been using RequireJS and it works perfectly. I use a lot of "window.document" to manipulate different DOM elements, but when I try to optimize it with r.js i get a ReferenceError: window is not defined which only happens with r.js.
Here is a minimal example of code that reproduces the issue:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body >
<div id="commentbox">
</div>
<script data-main="code/main" src="code/require.js"></script>
</body>
</html>
main.js:
require(["roomManager"], function (roomManager){
return {
}
});
roomManager.js:
define(["commentManager"], function(commentManager){
var commentHand = new commentManager.commentHand();
commentHand.init();
return{
}
});
commentManager.js:
define([], function(){
function commManager(getDisplayIdVariable){
var messagebox = window.document.getElementById("commentbox");
this.init = function(){
messagebox.innerHTML = "hi!";
}
}
return{
commentHand : commManager
}
});
This version works correctly without r.js but when I try to compile it by running r.js main.js. I get this:
var messagebox = window.document.getElementById("commentbox);
ReferenceError: window is not defined
at new new commManager
You cannot just do r.js main.js.
For one thing, you have to specify -o so that r.js performs the optimization. (r.js can be used for other things.)
You also have to pass configuration to r.js, either in a file, or on the command line. One possibility for you would be:
r.js -o name=main out=built.js
I've tried this with the code you show in your question and I get no errors.
I strongly suggest going over this documentation for r.js.
if your code is optional you can use
if (typeof window !== 'undefined') {
// Inside browser
}
{
// outside browser
}

Categories

Resources