Uncaught ReferenceError: _k is not defined - javascript

I am trying to import a module I made, however, I cannot access the function. Js tells me that it is not defined even though it is in the html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/#kagarisoft/csc/dist/css/common.min.css"
/>
<style>
.flex-buttons {
display: flex;
gap: 10px;
}
</style>
<!-- my module -->
<script type="module" src="https://cdn.jsdelivr.net/gh/Neyunse/kquery/dist/kquery.browser.min.js"></script>
<!-- <script type="module" src="https://cdn.jsdelivr.net/gh/Neyunse/kquery/dist/kquery.module.min.js"></script> -->
</head>
<body>
<div class="kg__container">
<!-- All content -->
<div class="flex-buttons">
<button id="hot" data-tag="hot" class="kg__button">
Get coffe hot list
</button>
<button id="iced" data-tag="iced" class="kg__button">
Get coffe iced list
</button>
<button id="clear" class="kg__button" disabled>Clear List</button>
</div>
<ul id="coffe"></ul>
</div>
<script src="./main.js"></script>
</body>
</html>
main.js
_k().load(() => {
_k('#hot').event('click', async () => {
_k("#hot").removeClass("kg-primary")
const { tag } = _k('#hot').getDataSet()
_k('#coffe').removeChildrens()
const r = await _k().remote(`https://api.sampleapis.com/coffee/${tag}`).get();
r.map(r => {
_k('#coffe').insertHTML(`<li><b>${r.title}:</b> ${r.description}</li>`)
})
_k('#hot').disableElement(true)
_k('#iced').disableElement(false)
_k('#clear').disableElement(false)
})
_k('#iced').event('click', async () => {
const { tag } = _k('#iced').getDataSet()
_k('#coffe').removeChildrens()
const r = await _k().remote(`https://api.sampleapis.com/coffee/_k{tag}`).get();
r.map(r => {
_k('#coffe').insertHTML(`<li><b>_k{r.title}:</b> _k{r.description}</li>`)
})
_k('#iced').disableElement(true)
_k('#hot').disableElement(false)
_k('#clear').disableElement(false)
})
_k('#clear').event('click', async () => {
_k('#coffe').removeChildrens()
_k('#iced').disableElement(false)
_k('#hot').disableElement(false)
_k('#clear').disableElement(true)
})
console.log(_k('button').getElements())
})
this module is a mini jquery clone I made, however, I'm having problems accessing it from a .js
the compiler I used was https://rollupjs.org/
I have the feeling that it is a problem when exporting the module, however, I don't know what could be the problem.
my module src: https://github.com/Neyunse/kquery/tree/master/src/lib

By looking at the code of the kquery library, you should either expose the _k object as a global variable inside your script:
window._k = _k;
Or store the result of the IIFE in a global variable:
const _k = (function () {
'use strict';
class Remote {
...
return _k;
})();
Otherwise, the variable _k only lives inside the private scope of the IIFE and cannot be accessed in the outer scopes.
Update: you can also do it by passing the --name parameter to rollup (preferred):
npx rollup main.js --file ../../dist/kquery.browser.min.js --format iife --name _k
This will automatically export the _k variable as a global object accessible to all scripts.

Related

importing a class returns error and breaks my existing function

I'm trying to import script.js into my app.js and it returns an error that says "Uncaught SyntaxError: import not found: script app.js:1:9" and also breaks getSelectedItems function and says that is also undefined. I included my HTML because I'm unsure if there could be an error there.
I'm trying to import this into app.js
export class script {
//Save movies into the local storage
saveIntoStorage(item) {
const items = this.checkStorage();
items.push(item);
// Add new array into the localStorage
localStorage.setItem("items", JSON.stringify(items));
}
// return movies from storage
checkStorage() {
let items;
// Check the localStorage
if (localStorage.getItem("items") === null) {
items = [];
} else {
items = JSON.parse(localStorage.getItem("items"));
}
return items;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<link rel="icon" href="./favicon.ico" type="image/x-icon">
</head>
<body>
<main>
<h1>Welcome to My Website</h1>
</main>
<script src="app.js" type="module"></script>
<script src="script.js" type="module"></script>
</body>
</html>
This is from my app.js
import {
script
} from "./script.js";
// Store the user input from dropdown menu into a new array
function getSelectedItems() {
const items = document.getElementsByClassName("selectVal");
myApp.results = [];
for (let i = 0; i < items.length; i++) {
const item = items[i];
const userInput = item.options[item.selectedIndex].value;
myApp.results.push(userInput);
}
}
Using type of module for the script tag fixed the error for me.
<script src="./app.js" type="module"></script>

"Unexpected token 'export'" error in Chrome, "export declarations may only appear at top level of a module" in firefox

In my snake.html file, I included main.js in module type
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake</title>
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/snake.css">
</head>
<body>
<div id="gameBoard"></div>
<script src="snake/main.js" type="module"></script>
</body>
</html>
In main.js, I imported some variables and functions from snake.js
import {speed, update as updateSnake, render as renderSnake} from "./snake.js";
updateSnake();
In snake.js, I imported a function from input.js
import {getDirection} from "./input.js";
export function update()
{
const direction = getDirection();
for(let i = 0; i < snakeBody.length; i++)
{
let segment = snakeBody[i];
segment.x += direction.x;
segment.y += direction.y;
}
console.log("Snake updated");
}
Lastly, in input.js I have an exported function named as getDirection
let direction = {x: 0, y: 0};
let lastDirection = {x: 0, y: 0};
export function getDirection()
{
lastDirection = direction;
return direction;
}
I did not write full code here in order to simplify the problem. When i open snake.html file in browser with live server, i got "Uncaught SyntaxError: Unexpected token 'export'" in Chrome. I searched through all results on google that i found, and no one worked.
(also in getDirection function, it says "'getDirection' is declared but its value is never read."
I really need help?

Sending data from html.index to functions.js file

Currently, I am stuck on working with a .html file which needs to send over data to a javascript file with functions. It looks as follows:
Data
let data = [
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]
HTML part calling javascript functions file with
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<title>Metabase Dashboard Carousel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="./src/carousel.js"></script>
</head>
<body onLoad="createFrames('test!')">
<button class="btn btn-primary " onclick=autoRun()>Start</button>
<button class="btn btn-primary " onclick=pause()>Pause</button>
</body>
</html>
Function which is called
function createFrames(text) {
console.log(text);
for(var i in data)
prepareFrame(data[i][0], data[i][1]);
};
Calling the function does give me a print of test! on the .html console with Mozilla inspector. However, running the rest of the script or actually using the data variable as input in the body onLoad function does not work.
How does this come and what would be a fix?
Also, not directly related what is a good way to load files between related .js / .yml / .json as when running the code in .html gives back that require is not defined?
Thanks for the help!
If you are able to modify your approach and are wanting to define the runtime data that will be used by the onload function you might try an approach like this. This uses an anonymous self executing function to run the prepareFrame commands once the DOM has been fully loaded. The data is supplied as an argument to the anonymous function and other functions can be defined within this scope so as to keep the whole thing neat.
(function(data){
const d=document;
// emulate actual functions with simple console cmds for testing only
const prepareFrame=(a,b)=>{
console.log('prepareFrame(%s,%s)',a,b)
};
const autoRun=(e)=>{console.log(e.target);return true};
const pause=(e)=>{console.log(e.target);return true}
d.addEventListener('DOMContentLoaded',()=>{
data.forEach(a=>{
prepareFrame(a[0],a[1])
});
d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
switch(this.dataset.task){
case 'start':return autoRun(e);
case 'pause':return pause(e);
}
}))
})
})([
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]);
<button class='btn btn-primary' data-task='start'>Start</button>
<button class='btn btn-primary' data-task='pause'>Pause</button>
For instance:
<!DOCTYPE html>
<html>
<head>
<meta content='text/html;charset=utf-8' http-equiv='Content-Type' />
<meta content='utf-8' http-equiv='encoding' />
<title>Metabase Dashboard Carousel</title>
<link href='//cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We' crossorigin='anonymous' />
<script src='//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
<script src='./src/carousel.js'></script>
</head>
<body>
<button class='btn btn-primary' data-task='start'>Start</button>
<button class='btn btn-primary' data-task='pause'>Pause</button>
</body>
<script>
(function(data){
const d=document;
// emulate actual functions with simple console cmds for testing only
const prepareFrame=(a,b)=>{
console.log('prepareFrame(%s,%s)',a,b)
};
const autoRun=(e)=>{console.log(e.target);return true};
const pause=(e)=>{console.log(e.target);return true}
d.addEventListener('DOMContentLoaded',()=>{
data.forEach(a=>{
prepareFrame(a[0],a[1])
});
d.querySelectorAll('button[data-task]').forEach(bttn=>bttn.addEventListener('click',function(e){
switch(this.dataset.task){
case 'start':return autoRun(e);
case 'pause':return pause(e);
}
}))
})
})([
["ID1", "URL1"],
["ID2", "URL2"],
["ID3", "URL3"],
]);
</script>
</html>

How can i use script src?

I am trying to use errLogin module in js code in html file.
THis is main.js file.
import puppeteer from "puppeteer"
const errLogin = false;
...
export default { errLogin }
THis is test.html file.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>main</title>
<style>
body {
font-family: Consolas, monospace;
}
</style>
<script src="./account.js"></script>
<script type="module">
import { errLogin } from "./main.js"
console.log(errLogin)
</script>
</head>
<body>
<div>
<p id="email"></p>
<p id="password"></p>
</div>
<script>
const CirculateData = () =>{
for (let key in account)
{
if (!errLogin) return account[key];
else return account[Number(key) + 1];
}
};
document.querySelector("#email").innerHTML = CirculateData().email
document.querySelector("#password").innerHTML = CirculateData().password
</script>
</body>
</html>
error message.
Uncaught TypeError: Failed to resolve module specifier "puppeteer". Relative references must start with either "/", "./", or "../".
this is folder structure.
How can I do it? How can I do it? How can I do it?How can I do it? How can I do it? How can I do it? How can I do it? How can I do it? How can I do it? How can I do it?
Type module work with src argument, then browsers don't know about import|export, you need Webpack or another bundler

importing javascript app lib does not work

I am trying to import https://github.com/tkurki/dnssd.js and make html file like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
<script src="/index.js"></script>
</head>
<body>
<section>
<h1>DNS-SD Browser</h1>
<div id="services"></div>
</section>
<script>
const dnssd = require('dnssd2');
// advertise a http server on port 4321
const ad = new dnssd2.Advertisement(dnssd.tcp('http'), 4321);
ad.start();
// find all chromecasts
const browser = dnssd2.Browser(dnssd.tcp('_http'))
.on('serviceUp', service => console.log("Device up: ", service))
.on('serviceDown', service => console.log("Device down: ", service))
.start();
</script>
</body>
</html>
But somehow it shows me error in console log:
Uncaught ReferenceError: require is not defined at index.js:1
Uncaught ReferenceError: require is not defined at index.js:18
What am I doing wrong please?
index.js contains:
var Advertisement = require('./lib/Advertisement');
var Browser = require('./lib/Browser');
var ServiceType = require('./lib/ServiceType');
var validate = require('./lib/validate');
var resolve = require('./lib/resolve');
var NetworkInterface = require('./lib/NetworkInterface');
module.exports = {
Advertisement: Advertisement,
Browser: Browser,
ServiceType: ServiceType,
tcp: ServiceType.tcp,
udp: ServiceType.udp,
all: ServiceType.all,
validate: validate,
resolve: resolve.resolve,
resolveA: resolve.resolveA,
resolveAAAA: resolve.resolveAAAA,
resolveSRV: resolve.resolveSRV,
resolveTXT: resolve.resolveTXT,
resolveService: resolve.resolveService,
};
The browser doesn't support require function
Use requirejs. You can also use it with jquery
You can learn about requirejs from here
Browser doesn't support require out-of-box. try adding this script tag to manually import require from its cdn.
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="/index.js"></script>

Categories

Resources