JS module throwing error upon declaration - javascript

I have a webpage (.ejs) that calls a separate file to contain the necessary JS, as here:
<html lang="en">
<head>
//stuff
</head>
<body>
//stuff
<script type="module" src="/public/js/p2p_logic.js"></script>
</body>
</html>
With the corresponding JS as here:
//p2p_logic.js
addEventListener("load", connect);
addEventListener("load", initialize);
//stuff
function connect() {
console.log("FIRED CONNECT");
} //connect()
function initialize() {
console.log("FIRED INITIALIZE");
import WebRTCAdaptor from "./public/js/webrtc_adaptor.js"
} //initialize()
As can be seen, the JS file calls an 'import'. I am having great difficulty getting this to be operative. I have never used an 'import' within a JS script file (attached to an HTML/EJS page) before. As written above, I am receiving this error:
Uncaught SyntaxError: Unexpected identifier p2p_logic.js:27
I have also attempted to use 'curly' brackets, as here:
import {WebRTCAdaptor} from "./public/js/webrtc_adaptor.js"
However this seems to have no effect. If I modify the JS file to 'import' on the initial line, as here:
//p2p_logic.js
import WebRTCAdaptor from "./public/js/webrtc_adaptor.js"
addEventListener("load", connect);
addEventListener("load", initialize);
//stuff
function connect() {
console.log("FIRED CONNECT");
} //connect()
function initialize() {
console.log("FIRED INITIALIZE");
} //initialize()
This throws a 404 error...which indicates a 'file not found'. Specifically:
Failed to load resource: the server responded with a status of 404 () webrtc_adaptor.js:1
That however is BS since the file is definitely in the './public/js' directory...the 'webrtc_adapter.js' file is in the same directory as the 'p2p_logic.js' file...but I am using an absolute path structure so I don't see how that would matter...?
I am beginning to think it is not possible to perform an 'import' of a file in this manner...I have never had an issue using an external JS file in conjunction with a HTML/EJS page before...however in those cases I never made usage of an 'import' statement.
Does anybody know if it is even possible to 'import' using an external JS file attached to a HTML/EJS page?

You have script tags inside your .js file which is throwing an error because those are html and you can't have that in a JavaScript file. Remove those and you should be good

I have the 'import' problem now resolved...I had included a period (".") within the path that should not have been there...which is why I was seeing a 404 error being thrown. The correct 'import' path should have been '/public/js/...' instead of './public/js/...' Thanks again to those that responded.

Related

How can I use a javascript function in index.html

I'm working on a react.js website where I'm supposed to call a javascript function in index.html. I'm experiencing some difficulties in calling the function.
This is what I'm doing in index.html
<head>
<script>
const getVar = getVarFromJs()
</script>
</head>
but whenever I do this, I get an error saying getVarFromJs is not defined. I also tried importing the function then I get an error saying "cannot use statement outside a module".
This is my js file:
let var = {};
export function getVarFromJs()
{return var;}
When I change the script type to module in index.html, I get this error:
Failed to load module script: Expected a Javascript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

How to use module from Github in javascript?

I am trying to use a library from GitHub found here: https://github.com/cubing/jsss
the readMe has an example of how to use it:
// index.html
<script src="index.js" type="module" defer></script>
<select id="eventID">
<option value="333" selected>3x3x3</option>
<option value="444">4x4x4</option>
</select>
<button id="new-scramble">New scramble</button><br>
<div id="scramble-string"></div>
// index.js
import { randomScrambleStringForEvent } from "scrambles";
const eventSelect = document.querySelector("#eventID");
const scrambleStringElem = document.querySelector("#scramble-string");
async function newScramble() {
scrambleStringElem.textContent += " ⏳";
const scrambleString = await randomScrambleStringForEvent(eventSelect.value);
scrambleStringElem.textContent = scrambleString;
}
document.querySelector("#eventID").addEventListener("change", newScramble);
document.querySelector("#new-scramble").addEventListener("click", newScramble);
newScramble(); // Initial scramble
The repo is full of so many folders I am not sure which ones I need. I used the src to and put this in a folder called libs with but I have no idea if this is right. I tried using the whole repo and it still didn't work. Whenever I try following the "full example" that they have I get an error. As someone who has never done this before:
Where do I put the index.js file
what files do I need to copy to my project to make this work
Putting index.html and index.js in the root directory I get the error
'Uncaught TypeError: Failed to resolve module specifier "scrambles". Relative references must start with either "/", "./", or "../".'
When adding the correct directory to scrambles, I get the error
'Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.'
In short I have no idea what I am doing and no idea how to use this in my project, please help...

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

requireJS, origin of the define statement

I'm working on a large project that uses Requirejs for dependency management, specifically the convention is for every file to have this pattern:
define(['dependency1', 'dependency2'], function (dependency1, dependency2) {
... some code ...
});
now I'm investigating a failure where some file is trying to require a dependency that no longer exists.
I'm getting this error from RequireJS:
GET https://some-location/some-file.js net::ERR_ABORTED
Uncaught Error: Script error for: some-file
http://requirejs.org/docs/errors.html#scripterror
at C (require.min.js:8)
at HTMLScriptElement.onScriptError (require.min.js:29)
at HTMLScriptElement.nrWrapper (...)
How can I know which file contains the faulty dependency?
Simply searching the project files is not good enough since it is a large project that spans across multiple code bases.
Is there a way to make RequireJS tell me who asked for it?
What version of requirejs are you using? I'm using 2.3.2 and the error output provide more info, take a look:
GET http://localhost:9090/requirejs/js/dependency1.js net::ERR_ABORTED
require.js:168 Uncaught Error: Script error for "home/dependency1",needed by: home/somefile
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:168)
at HTMLScriptElement.onScriptError (require.js:1735)
Please, note that the part that says needed by: home/somefile is telling us the file that is requiring the failed dependency. This is the small local test I did.
requirejs config
require.config(
{
paths: {
'home': './js'
},
callback: function() {
require(['home/somefile'], function(a) {
console.log(a);
});
}
}
);
./js/somefile.js
define(['home/dependency1'], function (dependency1) {
console.log(dependency1);
});
So, after getting the error Uncaught Error: Script error for "home/dependency1",needed by: home/somefile, we can say that the file requiring the failed dependency is PATH_TO_OUR_PROJECT/js/somefile.js. Remember that we need to pay attention to our paths in the require config.
You can play and test the Global requirejs.onError function but it won't give you more info than the regular requirejs output.
More info in Handling Errors from docs.
Hope it helps.
Following Castro Roy's answer i made a test to verify this is indeed issue of requireJS version.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Require Test</title>
<script data-main="main" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
</head>
<body></body>
</html>
main.js
requirejs(['someFile'], function(someFile) {
console.log('main executing')
});
someFile.js
define(['someDependency'], function (someDependency) {
console.log('someFile executing')
});
and someDependency.js obviously missing.
Results:
using requireJs 2.1.20 (used in my project)
GET http://localhost:63342/playground-simple/someDependency.js net::ERR_ABORTED
Uncaught Error: Script error for: someDependency
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.min.js:1)
at HTMLScriptElement.onScriptError (require.min.js:1)
Then again using requireJs 2.3.2
GET http://localhost:63342/playground-simple/someDependency.js net::ERR_ABORTED
Uncaught Error: Script error for "someDependency", needed by: someFile
http://requirejs.org/docs/errors.html#scripterror
at makeError (require.js:168)
at HTMLScriptElement.onScriptError (require.js:1735)
So clearly Yes.
This is an issue of version and not some unique behavior of my project and this information is given in the error message for later versions of require.
sadly i was not able to find any documentation for this change

Issues Integrating ACE Editor with Keystonejs App

It says here(http://ace.c9.io/#nav=embedding) just copy one of src* subdirectories somewhere into your project
I have put it in mykeystoneapp/public/js(my default home is mykeystoneapp/public)
Here are the errors I get:
1.Uncaught TypeError: $.cookie is not a function(ui.js:8)
2.Uncaught Error: Missed anonymous define() module: function …(require.js:141)
http://requirejs.org/docs/errors.html#mismatch
Here is my Jade code:
script(src='/js/ace/demo/kitchen-sink/require.js')
script.
require.config({paths: {ace: "/js/ace/build/src"}});
define('testace', ['ace/ace'],
function(ace, langtools) {
console.log("This is the testace module");
var editor = ace.edit("editor_container");
editor.setTheme('eclipse');
editor.session.setMode('javascript');
require(["/js/ace/lib/ace/requirejs/text!src/ace"], function(e){
editor.setValue(e);
})
});
require(['testace']);
Secondly if I put debugger in EventEmitter(https://github.com/ajaxorg/ace-builds/blob/master/src/ace.js#L3300)
I can see it’s properly reaching EventEmitter._dispatchEvent with
eventName=‘changeMode’ but it returns without any operation as there are no !listeners or defaultHandler
editor.session.setMode('javascript'); is wrong, it should be editor.session.setMode('ace/mode/javascript'); instead. Same for theme which is supposed to be ace/theme/eclipse.
error in ui.js is not related to ace, since ace doesn't have a file named ui.

Categories

Resources