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

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.

Related

Calling javascript code with 'require' from flutter web

So I saw this tutorial about calling javascript functions from flutter web: https://fireship.io/snippets/using-js-with-flutter-web/ but I ran into a problem trying to use 'require'. I have 3 files:
main.dart:
import 'dart:js' as js;
void main() async {
js.context.callMethod('demo', []);
}
test.js:
exports.testFunction = function() {
console.log("test");
}
demo.js:
test = require("./test");
function demo() {
console.log("called");
test.testFunction();
}
and my index.html file incudes the lines:
<head>
<script src="test.js" defer></script>
<script src="demo.js" defer></script>
(...)
When I run my code it prints 'called' but then it crashes and throws: 'ReferenceError: test is not defined'.
I'd like to know how to use require so I can use multiple js files and node packages

load js file in requirejs-config.js in magento2

how to load this js file in requirejs?
<script type="module" src="https://unpkg.com/#google/model-viewer/dist/model-viewer.min.js"></script>
my requirejs-config.js file=?
var config = {
paths: {
modelviewer: "Ajith_CustomModule/js/modelviewer.min",
.....
.....
.....
and load this file in my phtml file
<script type="module">
require(['jquery'.......,'modelviewer'],function($,..,model){
});
</script>
.....
.....
.....
shows this error =>
Uncaught SyntaxError: Unexpected token 'export'
anybody please help me to fix this problem.
Thanks in advance
RequireJS does not support native JS modules. You have to load it as regular JS module, working example:
<script type="module">
import { ModelViewerElement } from 'https://unpkg.com/#google/model-viewer/dist/model-viewer.min.js';
console.log(ModelViewerElement);
</script>
(tested on Chrome 96)

Using an NPM dependency in an HTML page

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.

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

Typescript include modules in browser?

I am just getting started with TypeScript (and front end development in general) coming from a c# background so sorry if this is a really basic question, but I can't figure out where I'm going wrong...
What I'm trying to do for now is create a really basic program to retrieve some sample data from a url in JSON format, parse to TS classes, and display it on the page.
In order to get the json response I found this answer that recommends using a node package. I got it installed and it seems to be ok (at least TS doesn't give me any errors).
I also figured out that I need to compile (not sure if that's the right term?) with Browserify to make it browser compatible since it's using a node module. I did that but now when I try to run in a browser it's telling me my method is not defined.
export class Keynote {
KeyValue: string;
Description: string;
Parent: string;
}
Retrieval class is:
import {Keynote} from "./Keynote";
import * as request from "request-promise-native";
function GetKeynotes(): Array<Keynote> {
const baseUrl = 'https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteProvider.php';
var options = {uri: baseUrl};
const result = JSON.parse(request.get(options));
return result;
}
and html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Keynotes Testing</title>
<script src="bundle.js"></script>
<script>
function Retrieve() {
var notes = GetKeynotes();
document.getElementById('container').innerText = JSON.stringify(notes);
}
</script>
</head>
<body>
<div>
<button content="Get some notes" onclick="Retrieve()">Get some notes</button>
</div>
<div id="container">
</div>
</body>
</html>
Browserify is really long so I didn't want to copy here but you can see it at https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteDisplay.html in the source if you want.
When I click the button I get this error in the browser:
KeynoteDisplay.html:9 Uncaught ReferenceError: GetKeynotes is not defined
at Retrieve (KeynoteDisplay.html:9)
at HTMLButtonElement.onclick (KeynoteDisplay.html:16)
Retrieve # KeynoteDisplay.html:9
onclick # KeynoteDisplay.html:16
GetKeynotes is defined in my typescript, and on the 5th line of bundle.js I see a function with that name... Why is it undefined?
UPDATE
Ok I have played with jspm and SystemJs but I still don't have something right. I referenced the module with jspm and did a bundle to build.js and uploaded the whole thing just to make sure everything is there. Here are the tags in my html for scripts:
<script src="../../jspm_packages/system.js"></script>
<script src="../../config.js"></script>
<script src="build.js"></script>
<script>
System.import("Sandbox/TypeScript/build.js")
function Retrieve() {
System.import("Sandbox/TypeScript/build.js")
var notes = GetKeynotes();
document.getElementById('container').innerText = JSON.stringify(notes);
}
</script>
When I press the button I can debug in my function, but it still gives the error, 'GetKeynotes is not defined' just like before... Again I can see a function with that name in the build.js file so I don't understand why it's not finding it.
I also tried System.import("Sandbox/TypeScript/KeynoteRetrieval.js") but it gives the error:
Uncaught (in promise) Error: (SystemJS) Node tls module not supported in browsers.
Error loading https://revolutiondesign.biz/Sandbox/TypeScript/KeynoteRetrieval.js

Categories

Resources