Calling javascript code with 'require' from flutter web - javascript

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

Related

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.

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.

Mocha, "require is not defined" when test in browser

I'm using Mocha 5.2.0, npm 6.1.0, and I'm trying to test in Chrome browser.
But When I run the test, the browser says "require is not defined".
I want to see the test result in browser, but it works in terminal.
I'm not using build system like webpack etc.
test/test.js
var assert = require("assert");
describe("Array", function() {
describe("#indexOf()", function() {
it("should return -1 when the value is not present", function() {
assert.equal([1,2,3].indexOf(4), -1);
});
});
});
index.html
...
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.css" rel="stylesheet">
...
<body>
<div id="mocha"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/5.2.0/mocha.min.js"></script>
<script>
mocha.setup("bdd");
</script>
<script src="test/test.js"></script>
<script>
mocha.checkLeaks();
mocha.run();
</script>
</body>
package.json
{
"scripts": {
"test": "mocha"
}
}
Edited Karthikeyan
index.html
<script data-main="test/test.js" src="require.js"></script>
require.js:168 Uncaught Error: Module name "assert" has not been loaded yet for context: _. Use require([])
Require.js is missing . Import require.js inside your body before importing mocha.js

HTML page not running JavaScript (transpiled by Babel)

I'm trying to port my JavaScript source code to JavaScript ES6. To acomplish this I have so far:
1) installed Babel to my project folder
2) created .babelrc file
3) defined the file watcher in my WebStorm to auto transpile JavaScript files.
Transpiling seems to work well, the "older" syntax JavaScript files get created in a dist folder. However, when I try to run my transpiled code (added in a .html file) the alert test doesn't show up when using import statement.
Here's the source code:
arquivo.js
let test = 'Alert from Arquivo.js';
export {test};
main.js
import {test} from "./arquivo";
alert(test);
After auto transpile:
arquivo.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var test = 'Alert from Arquivo.js';
exports.test = test;
//# sourceMappingURL=arquivo.js.map
main.js
"use strict";
var _arquivo = require("./arquivo");
alert(_arquivo.test);
//# sourceMappingURL=main.js.map
This is my index.html file inside same transpiled JavaScript files folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<!--
main.js is the after
transpiled code
-->
<script src="main.js"></script>
</head>
<body>
</body>
</html>
Browser console reports this:
Uncaught ReferenceError: require is not defined
at main.js:3
How to avoid this problem?

Using express-babelify-middleware with FeathersJS

I am trying to use express-babelify-middleware
with FeathersJS and the error shows up in the browser console:
ReferenceError: main_run is not defined
I take this to mean that babelify is not working or I am using it incorrectly as main_run is in the global namespace of the src in my html file.
Here is my setup using the structure from feathers generate:
public/index.html:
<!DOCTYPE html>
<html>
<head>
<title>babelify test</title>
<script src="main.js"></script>
<script>
main_run()
</script>
</head><body>
<p>Testing feathers with babelify</p>
</body></html>
public/main.js
const external_module = require('./test')
function main_run(){
external_module()
}
public/test.js
module.exports = function(){
console.log("Hello world for an external module")
}
among the .uses of src/app.js:
...
const babelify = require('express-babelify-middleware')
...
app.use(compress())
.options('*', cors())
.use(cors())
//the line that is not working:
.use('/main.js', babelify( path.join(app.get('public'), 'main.js') ))
.use(favicon( path.join(app.get('public'), 'favicon.ico') ))
.use('/', serveStatic( app.get('public') ))
When I visit localhost:3030/main.js I can see the file, but the functions look to be in a function of their own, so I don't know how to get into that function.
Silly problem, one can't access browserified code in the html file that calls it. So public/index.html can't access main_run unless it is attached to the window object. There is a similar question
here.
Other than that, my code works perfectly.
In main.js place the following code at the bottom:
window.main_run = main_run
Then in index.html replace the main_run() line with:
window.main_run()
This will write the contents of test.js to the console.

Categories

Resources