How can i use script src? - javascript

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

Related

Uncaught ReferenceError: _k is not defined

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.

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>

How to I assign the ttf font file in the vfs_fonts.js?

I am trying to add the custom fonts into vfs_fonts.js but I didn't understand what needs to be written in the value field of window.pdfMake object?
I have my key as "MyFont.ttf" and I know that value is nothing but ttf file. My ttf is a physical file not a set of characters. How do I fill the value field?
window.pdfMake = window.pdfMake || {}; window.pdfMake.vfs = {
"Roboto-Italic.ttf": "AAEAAAASAQAABA",
"Roboto-Medium.ttf": "AAEAAA",
"MyFont.ttf":"???????????????????"
}
Thank you
/* Read the documenation at https://github.com/bpampuch/pdfmake
specially the readme file */
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>my first pdfmake example</title>
<script src='build/pdfmake.min.js'></script>
<script src='build/vfs_fonts.js'></script>
</head>
<body>
<script>
// works great with the default vfs_fonts.js
pdfMake.fonts = {
Roboto: {
normal: 'Roboto-Regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'Roboto-Italic.ttf',
bolditalics: 'Roboto-MediumItalic.ttf'
}
};
// open the PDF in a new window
pdfMake.createPdf(docDefinition).open();
</script>
</body>

returned 404 error when load js file

I get an error when i would like to render html file which contains a script link on js file.
But when i load page i get this error :
Started GET "/views/script.js" .... Returning 404
my folder is like this
|--todolist
|--main.go
|--views/
|--index.html
|--script.js
main.go
package main
import (
"github.com/zenazn/goji"
"html/template"
"net/http"
)
func renderHTMLPage(w http.ResponseWriter, path string) {
t, err := template.ParseFiles(path)
if err != nil {
panic(err)
}
t.Execute(w, nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
renderHTMLPage(w, "./views/index.html")
}
func main() {
goji.Get("/", Index)
goji.Serve()
}
views/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Le titre du document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="script.js"></script>
<h1>To-Do List </h1>
<ul id="todolist">
<li> Hello <button>Delete</button></li>
<li> Wesh <button>Delete</button></li>
</ul>
<input type="text" id="new-text" /><button id="add">Add</button>
</body>
</html>
views/script.js
function addListItem() {
var text = $('#new-text').val()
if (text != "") {
$('#todolist').append('<li>'+text+'<button id="dede" name=\"' + i + '\">Delete</button></li>')
}
$('#new-text').val("")
}
function deleteItem() {
$(this).parent().remove()
}
$(function() {
$('#add').on('click', addListItem);
$("#todolist").on("click", "#dede", deleteItem)
});
How can I do to make it properly load the js file ?
And what is the best way to create an app who use only jquery/javascript with a golang api on architecture ?
Thank you
You need to either:
Serve from the directory containing /views - e.g. goji.Get("/views/*", http.FileServer(http.Dir("/Users/matt/Desktop/views/")))`
Use http.StripPrefix (recommended)
The below allows you to decouple the path from the directory name:
func main() {
goji.Get("/views/*", http.StripPrefix("/views", http.FileServer(http.Dir("/Users/matt/Desktop/views/"))))
goji.Get("/", Index)
goji.Serve()
}
I'd recommend against serving from the 'root' - /*. Better to serve from a dedicated assets path as it makes it easier when looking at caching, interacting with CDNs, etc.
In this particular case code should look like
goji.Get("/", Index)
goji.Get("/*", http.FileServer(http.Dir("./views")))
goji.Serve()
But I must say keeping template and static files in same directory is bad idea as well as serving static files from root.

not able to do routing properly in page.js

I am using page.js for routing in a Single Page Application. For testing purpose, I am using npm http-server.
I am not able to do routing. I am not sure what I am missing. following is my code:
index.html:
<html>
<head>
<title>test page!</title>
<script src="/js/libs/page.js"></script>
</head>
<body>
this is body of test
Simple test
<script type="text/javascript" src="/js/routes.js"></script>
</body>
</html>
routes.js
function initRoutes () {
var testRoutes = {
test : function (context, next) {
alert("testing");
if(next){
next();
}
},
test2 : function (context, next) {
alert("I am jon snow, I know nothing.");
}
};
page.base('/');
page('/', testRoutes.test);
page('/test', testRoutes.test2);
page('/two-args', testRoutes.test, testRoutes.test2);
page();
}
initRoutes();
from my http-server, I am accessing http://0.0.0.0:8081. I am getting an test as alert, but I am not getting the alert for route http://0.0.0.0:8081/test.
I am not sure what I am missing. Please let me know if you need anything else.

Categories

Resources