Jquery error '$ is not a function' in Node.js - javascript

I am getting the console error '$ is not a function' when using Jquery with Jsdom. I am using the latest Jquery version 3.3.1 and Jsdom 13.2.0. I am also using Browserify in order to utilize require.
main.js
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = jQuery = require('jquery')(window);
$("body").click(function() {
$("#name-tag").fadeOut("slow", function() {
// Animation complete.
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale = 1.0, maximum-scale=1.0, user-scalable=no"
/>
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="scss/styles.css" />
<script src="js/bundle.js"></script>
</head>
<body>
<div id="name-tag">
<h1>Hello World</h1>
</div>
</body>
</html>

Get rid of (window) after require('jquery'), so it should just be:
var $ = jQuery = require('jquery');
What you've written is redefining $ and jQuery as if you'd done:
jQuery = require('jquery');
var $ = jQuery = jQuery(window);
BTW, you can't declare two variables by chaining assignments like that. Only the first variable is being declared locally, the second one is an assignment without a declaration. If you want to declare two variables and given them the same value, do it in two steps:
var $, jQuery;
$ = jQuery = require('jquery');

Related

Uncaught ReferenceError: exports is not defined //year 2020

I'm stuck. I tried many solutions but none of them works.
Trying to implement a module, I get this error message:
Uncaught ReferenceError: exports is not defined
I tried solution from Stack Overflow, but it does not work. Changing anything in tsconfing does not make any difference. I added var exports = {}; into scripts in HTML file and error changes from "exports" to "require" - dead end.
server node:
var fs = require('fs');
const express = require('express');
var path = require('path');
var { request } = require('http');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3533);
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="testing site">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>simple testin </title>
</head>
<body >
</body>
<script type="text/javascript" src="webscripts/run_scripts.js"></script>
<script type="text/javascript" src="webscripts/library.js"></script>
</html>
library.ts:
export function appearSomeTestingSentence() {
document.write('111111');
};
library.js:
"use strict";
exports.__esModule = true;
exports.appearSomeTestingSentence = void 0;
exports.appearSomeTestingSentence = function () {
document.write('111111');
};
run_scripts.ts:
import {appearSomeTestingSentence} from './library.js';
appearSomeTestingSentence();
run_scripts.js:
"use strict";
exports.__esModule = true;
var library_1 = require("./library");
library_1.appearSomeTestingSentence();
Finally i sort it out. I had to delete *.js files before i compile with tsc and i had to restart tsc after changing something in tsconfig. Problem solved after
changing module to"module" : "ESNext" in tsconfig file.

Routing(?) in Vanilla JS

I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!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>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

Localhost not loading module

I am using modern Javascript MyClass.js
export default class MyClass {
constructor(x) {
this.val=x? x: "Hello!"
console.log("MyClass:",x)
}
}
at my http://localhost/myfolder/mypage.htm, with the source below,
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
<script type="module" src="./MyClass.js"></script>
<script>
'use strict';
document.addEventListener('DOMContentLoaded', function(){
alert(123)
let x = new MyClass(11);
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
Why console say "Uncaught ReferenceError: MyClass is not defined"?
PS: this question is a complement for this other about using ES6+ with browser+NodeJs.
NOTE: using UBUNTU ith Apache's Localhost... Some problem with myfolder a symbolic link to real folder? at /var/www/html I used ln -s /home/user/myRealFolder/site myfolder
you need to import the module before using it
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8" />
<script type="module" src="./MyClass.js"></script>
<script type="module" id="m1">
// script module is an "island", not need onload.
'use strict';
import MyClass from './MyClass.js';
let x = new MyClass(11); // we can use here...
console.log("debug m1:", x) // working fine!
window.MyClassRef = MyClass; // "globalizing" class
window.xRef = x // "globalizing" instance
</script>
<script> // NON-module global script
document.addEventListener('DOMContentLoaded',function(){
// only works after all modules loaded:
console.log("debug:", window.xRef) // working fine!
let x = new window.MyClassRef(22); // using class also here,
console.log("debug:", x) // working fine!
}, false); //ONLOAD
</script>
</head>
<body> <p>Hello1!</p> </body>
</html>
There are two ways to use an imported class:
at module scope (script m1): you can use new MyClass(), and can "globalize" instances (e.g. xRef) or the costructor's class (MyClassRef).
at global scope: to work together other libraries or with main script, use a global reference, e.g. new window.MyClassRef().
All this solution relies upon "static import"...
Optional dynamic import
You can use also import with ordinary default <script> (no type="module"), and no "onload", using this solution, instead the last script:
<script>
'use strict';
import('./MyClass.js').then(({default: MyClass}) => {
alert(123) // async block
let x = new MyClass(11);
});
</script>
See dynamic import.

How to access client window javascript global variable with Spectron

I'm trying test of Electron app with Spectron.
But I can't test client window javascript global variable.
Here is my simplified code.
Please help me.
Thanks.
index.html
<!DOCTYPE html>
<html lang="ja">
<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 ELECTRON</title>
<script type="text/javascript" src="script.js"></script>
<link href="./style.css" rel="stylesheet">
</head>
<body>
</body>
</html>
script.js
let mode;
function onload_func(){
mode = 'normal';
}
window.onload = onload_func;
spec.js
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
let app;
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
app = new Application({
path: electronPath,
args: [path.join(__dirname, '../src')]
})
return app.start()
})
afterEach(function () {
if (app && app.isRunning()) {
return app.stop()
}
})
it('initial mode',function(){
assert.equal(app.client.mode,'normal');
})
})
I'm not sure if it will solve your specific tests, but app.browserWindow should do the trick since as they say:
It provides you access to the current BrowserWindow and contains all
the APIs.
Note that it's an alias to require('electron').remote.getCurrentWindow()
Read more: https://github.com/electron/spectron#browserwindow

Phonegap plugin - module.exports

How are objects passed between the plugin's javascript and the javascript of the view? I'm playing around with an example code from the "apache cordova 3 programming" book and i'm stuck...
In my plugin.xml I set the namespace to "mool"
<js-module src="plugin.js" name="moool">
<clobbers target="mool" />
</js-module>
plugin.js
var mol = {
calculateMOL : function() {
return 42;
}
};
var molll = {
calculateMOLLL : function() {
return 42222;
}
};
module.exports = molll;
module.exports = mol;
index.html
<!DOCTYPE html> <html>
<head>
<title>Meaning of Life Demo</title>
<meta http-equiv="Content-type" content="text/html;
charset=utf-8">
<meta name="viewport" content="user-scalable=no,
initial-scale=1, maximum-scale=1, minimum-scale=1,
width=device-width;" />
<script type="text/javascript" charset="utf-8"
src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady,
false);
};
function onDeviceReady() {
//alert("onDeviceReady");
};
function doMOL() {
var res = mool.calculateMOL();
alert('Meaning of Life = ' + res);
};
function doMOLL() {
var res = mool.calculateMOLLL();
alert('Meaning of Life = ' + res);
};
</script>
</head>
<body onload="onBodyLoad()">
<h1>MoL Demo</h1>
<p>This is a Cordova application that uses my custom
Meaning of Life plugin. </p>
<button onclick="doMOL();">Button1</button>
<button onclick="doMOLL();">Button2</button>
</body>
</html>
But when I run it only the second button works ... can somebody give me an explanation to this?
I already tried exporting both objects at once like:
module.exports = molll, mol;
but it still won't work...
This is a late comment but might benefit someone else. What worked for me was something similar to the following:
Try rewriting the plugin.js functions as follows:
module.exports.calculateMOL = function() { return 42; };
module.exports.calculateMOLLL = function() { return 42222; };
Drop the two export statements at the end (i.e. module.export = mol; and = molll;)
This should allow the two methods to be accessed as shown in the index.html file above.
It seems as if per definition it only assignes one object!
"The clobbers element specifies the JavaScript object assigned to the loaded JavaScript object."
I notice that in an app I had built, the module.exports property is taking an array, like below. That would allow you to put both your items in there(?) (I am just showing one object of the array in this snippet.)
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/org.apache.cordova.dialogs/www/notification.js",
"id": "org.apache.cordova.dialogs.notification",
"merges": [
"navigator.notification"
]
}, etc

Categories