Import and export issue Javascript (No node.js) - javascript

Hello !
I tried using import/exports for the first time, and I have this issue in my code :
The requested module '../Ajout/script.js' does not provide an export named 'flagMap'
I have these files Supprimer.js, containing at the first line :
import{flagMap, findUrl, createUrl,texteValide} from '../Ajout/script.js';
And in Ajout.js contained in another forlder in the parent folder:
var flagMap={/*really long map*/}
function findUrl(isoCode){/*long url finder*/}
function createUrl(svgUrl) {
return `https://upload.wikimedia.org/wikipedia/${svgUrl}`;
}
function texteValide(element){/*text validation for a form*/}
export{flagMap,findUrl,createUrl,texteValide};
/*
other non-exported functions
*/
There is the type="module" in my html when I'm importing the script, and my Ajout.js also contains other functions, maybe it's causing issues ?
Also : The issue is not only flagMap but every import, because it shows another file if I remove flagMap from the imports

This works fine for me:
<!-- index.html -->
<html>
<head> ... </head>
<body>
<script type="module" src="path/to/Supprimer.js"></script>
</body>
</html>
// Ajout.js
var flagMap = {
// ...
};
function findUrl(isoCode) {
// ...
}
function createUrl(svgUrl) {
// ...
}
function textValide(element) {
// ...
}
// Export functions and variables
export {
flagMap,
findUrl,
createUrl,
texteValide
};
// Supprimer.js
import { flagMap, findUrl } from "path/to/Ajouter.js";
console.log(flagMap); // Prints map
findUrl("EN"); // Can call function

Related

keeping scope while using import statment

I have three scripts: main.js, helper.js and module1.js. I need to include module1.js in helper.js, buf if I do this I'm getting an error message. It seems like the moment I use the tpye="module" tag on helper.js it's scope shifts. So how do I achieve the following without an error: (I don't want to make helper.js a module, which would solve the problem, because than I have to manualy import everything.)
index.html
<html>
<head>
<title></title>
</head>
<body>
<script type="module" src='helper.js'></script>
<script type="module" src='main.js'></script>
</body>
</html>
module1.js
export { f1 }
function f1() {
/* DIFFERENT STUFF */
return 0;
}
main.js
// import THINGS from STUFF;
(() => {/*STUFF*/})();
let res = importantValue;
helper.js
import { f1 } from "./module1.js";
const importantValue = f1();
Error Message:
main.js: Uncaught ReferenceError: importantValue is not defined

Script trying to define a function from the wrong file

I want to call a function 'addArray' in a separate .js file called 'main.js'
When I run this code, I get an error saying the 'addArray' is not defined in checkout.js
I don't want it to look for the function in checkout.js, I want it to look for the function in main.js
I am using node.js
<body onload="myFunction()">
<script src = "https://www.paypalobjects.com/api/checkout.js"></script>
<script type = "text/javascript" src = "main.js"></script>
<div class="container">
</div>
<script>
paypal.Button.render(
{
onAuthorize: function(data, actions)
{
return actions.payment.execute().then(function()
{
// Show a confirmation message to the buyer
days = 30
localStorage.setItem("days", days);
inputDays = JSON.parse(localStorage.getItem('days'));
inputName = localStorage.getItem('name');
window.alert('Thank you for your purchase!');
console.log(inputDays);
console.log(inputName);
addArray();
});
}
}, '#paypal-button');
I had to delete most of the intermediate non essential code for the purpose of submitting this question
So... There are a few things I think you should check for.
If you are using commonJS, be sure that you are exporting the addArray function like so: module.exports = {addArray}; Then require it from your main.js file.
If you are using es6 syntax, you can export it like export default addArray or export {addArray}, then import it in your main.js file using the import {addArray} from... or import addArray from ... depending on the export style you used.

Kotlin to JS Iterator is not a function

I am currently implementing a Part-of-speech-tagger in Kotlin and when building / running on JVM everything works just fine (the tagger tags things correct and the program is reasonable fast when it comes to tagging sentences). However when I exported the program to JS I get the following error message:
TypeError: tags.iterator is not a function. (In 'tags.iterator()', 'tags.iterator' is undefined)
Trigram — Trigram.kt:13
Globaler Code
evaluateWithScopeExtension
(anonyme Funktion)
_wrapCall
Things I tried:
1. I had this exact JS-Code within the HTML-File, then it worked but the performance was awful (took 2-3 seconds to tag one sentence, if I tag the same sentence via the JVM it takes like 0.2 seconds or less).
2. replaced for(word in tags)with for(word in tags.toList(), the iterator was still undefined
I am on macOS using Safari, the error occurs on chrome as well.
Thank you for your help!
Kotlin-Class producing errors
class Trigram (private val probabilities: Probabilities, tags: List<String>){
// Creating the list mit all possible tags
init {
val list = ArrayList<String>()
for(word in tags) { // This is where the error occurs
list.add(word)
}
}
JS-File that returns the testing-strings
function getTags() {
return ["NN", "$.", "$(" ... , "PPOSS"]
}
function getJsonString() {
return ... // Returns a valid JSONString
}
Test-HTML-File
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Part-of-speech-tagger</title>
<!-- Loading kotlin.js -->
<script src="../../../js/packages_imported/kotlin/1.3.72/kotlin.js" charset="utf-8"></script>
<!-- Loading kotlinx-serialization-kotlinx-serialization-runtime -->
<script src="../../../js/packages_imported/kotlinx-serialization-kotlinx-serialization-runtime/0.20.0/kotlinx-serialization-kotlinx-serialization-runtime.js" charset="utf-8"></script>
<!-- Loading the generated js file -->
<script src="../../../js/packages/postagger/kotlin/postagger.js" charset="utf-8"></script>
<!-- Loading the js file containing the strings -->
<script src="strings.js" charset="utf-8"></script>
</head>
<body>
<h1>This is a test html file to check for js support</h1>
</body>
</html>
build.gradle
plugins {
id 'java'
id 'org.jetbrains.kotlin.multiplatform' version '1.3.72'
id 'org.jetbrains.kotlin.plugin.serialization' version "1.3.70"
}
group 'my group'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
jcenter()
maven { url "https://kotlin.bintray.com/kotlinx" }
}
kotlin {
// JVM Target
jvm() {
withJava()
jvmJar {
manifest {
// Specify main-class
attributes(
'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
'Main-Class': 'postagger.MainKt'
)
}
}
}
targets {
fromPreset(presets.js, 'js') {
nodejs {}
configure([compilations.main, compilations.test]) {
tasks.getByName(compileKotlinTaskName).kotlinOptions {
sourceMap = true
moduleKind = "umd"
metaInfo = true
}
}
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:0.20.0"
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
jvmMain {
dependencies {
implementation kotlin('stdlib-jdk8')
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0"
}
}
jvmTest {
dependencies {
implementation kotlin('test')
implementation kotlin('test-junit')
}
}
jsMain {
dependencies {
implementation(kotlin('stdlib-js'))
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.20.0"
}
}
jsTest {
dependencies {
implementation kotlin('test-js')
}
}
}
}
In a similar (although not same) environment, I had the same problem: a correct kotlin file compiled to javascript code that would fail with
iterator is not a function.
The object missing the iterator method was deserialized from a Json string.
If this is the case for you, then making sure that all the below conditions hold:
build.gradle contains the serialization plugin
plugins {
...
id 'org.jetbrains.kotlin.plugin.serialization' version "1.3.70"
...
}
deserialization (json string to object) uses
kotlinx.serialization.json.Json(JsonConfiguration.Stable)
.parse<YourObject>(jsonString)
instead of kotlin.js.JSON.parse(jsonString) method.
Class YourObject has the #Serializable annotation
solved the problem for me.

Why isn't html running javascript I import when I use import-export

My code works fine when I add my module straight into the html code, but it won't load it when I try to first import the module to a different javascript file.
I've tried exporting everything, from my module.
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
It should add elements to the div. But it wont do it unless I straight up use the sidebarmodule.js. I want to do it through the app.js
EDIT
Found the problem!
Didn't initialize index in the for loop.
EDIT2
And the type="module" which needed to be added
When you load your app.js in your html file, try to add:
<script type="module" src="js/app.js"></script>
That should work when you want to use ESModules. But please update us regardless :)
Update:
Ok after creating a project myself using your HTML and JS, I found a few errors.
First: When using ESModules, you can't use any functions in the JS through your HTML, you will have to inject everything from the app.js.
index.html:
<body>
<div id="sidenav">
Here be the links to other pages
</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script type="module" src="js/app.js"></script>
app.js:
import { createSidebar } from './visualModules/sidebarmodule.js';
cumulator();
function cumulator() {
createSidebar()
}
Notice two things: at the end of the import, since we are not using a compiler, the modules do not recognize files without their extension. So I had to add .js to sidebarmodule. Secondly, I had to invoke cumulator function within the app.js file (like I said earlier, you cannot use any module functions outside their scope. There are no global variables with ESModules).
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(var index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
You did not declare index inside your for loop, so I just added a var.
Hope this helps.
import is asynchronous in Javascript (in a browser, not Node.js) so you're calling createSidebar() before the module is loaded. You can use import to return a promise so you can execute code once it is completed.
Remove the embedded Javascript from your html, but leave the link to app.js. Then change app.js to this...
import("./visualModules/sidebarmodule")
.then((sidebar) => {
sidebar.createSidebar();
});

How to pass an object to an module in require.js?

I have these js files:
main.js:
requirejs(['app']);
app.js:
define(['messages'], function (messages) {
alert(messages.getHello());
});
messages.js:
define(['global'],function () {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
global.js:
define(function () {
var stateObj = {hello:"test!"};
return {
getObj: function () { return stateObj; }
};
});
and index.html as:
<!DOCTYPE html>
<html>
<head>
<!-- Include the RequireJS library. We supply the "data-main" attribute to let
RequireJS know which file it should load. This file (scripts/main.js) can
be seen as the entry point (main) of the application. -->
<script data-main="scripts/main" src="lib/require.js"></script>
</head>
<body>
<h1>Example 2: load module using explicit dependency syntax</h1>
</body>
</html>
However when I open index.html, I get the below error in console:
Uncaught ReferenceError: global is not defined messages.js
where I'm making mistake?
You just need to set global as an argument to messages.js' function. requirejs will pass it in for you.
messages.js:
define(['global'],function (global) {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
This has the neat side effect that it is impossible to reference a module without declaring it as a dependency.

Categories