I'm using Acorn to parse some syntactically valid JavaScript code into an ESTree for further processing. It appears that Acorn does some semantic checks too - in particular it throws an error for duplicate declarations. For example, parsing the following code throws an error of Identifier 'f' has already been declared:
function f() { return 1; }
function f() { return 2; }
I do not want such semantic errors to be checked - I'm doing custom processing on the resultant ESTree, so the semantic validity of the source code does not matter to me.
I've looked though the Acorn options for the parse(input, options) function, but I could not find anything that sounds like what I want.
Is there a way to disable such semantic checking?
It seems like there is no proper way to disable semantic validation. I managed to get what I want with an ugly hack, by overriding the raiseRecoverable method.
This worked for me (note that I'm using TypeScript here, but it would of course be possible to do the same in plain JavaScript):
import { Parser } from "acorn";
class SyntacticParser extends Parser {
raiseRecoverable(pos: any, message: string) {
if (message.includes("Identifier ") && message.includes(" has already been declared")) return;
(Parser.prototype as any).raiseRecoverable.call(this, pos, message); // weird call syntax required because the TypeScript types for Parser doesn't contain the `raiseRecoverable` method
}
}
It's an ugly hack because I'm filtering out the duplicate declaration message based on the stringified error message. However, there does not appear to be a better way.
In short, I'm trying to call an external JS function which my 3rd party required me to include, in order to use their API, but doesn't work as it supposed to.
From what I've read, I am supposed to use, for example, window.extFn() after including the external JS in my index.html which contains the extFn() like so
<script src="https://example.com/external.js"></script> <-- actually not like this, see update 2 as I imported the library locally
...and supposed to use it like how it was answered here: Call external Javascript function from react components regardless of whether the said function is inside a file or simply defined on index.html <script> section. This had worked on the JS file I created for testing this.
//File: test.js
function test() {
return "Hello";
}
...imported the JS file with script tag like usual, and using console.log(window.test()) in my React Component's render() returned Hello.
I tried moving the import to HTML head from body and vice-versa but the error I'm still getting is:
TypeError: window.extFn is not a function
QuickCheckout.render
....
22 | }
23 |
24 | render() {
> 25 | window.extFn({
26 |
View compiled
▶ 20 stack frames were collapsed.
And when I look into my browser console, for some reason I have (which seems to be the key problem)
Uncaught SyntaxError: Unexpected token < external.js:1
Tried console.log(window.extFn) and it returns undefined
So I think it might be possible that the said JS is the problem itself, but I'm at my wit's end with this. Meanwhile I had emailed my 3rd party support team, does anyone have any advice on this? Thank you very much.
UPDATE: Now my test.js file above, which had worked in my experiment, produces the Unexpected token < error as well in my console...
UPDATE 2: I apologize for your problems. But I actually imported the JS from local source due to having to port their library as they had jQuery 2 instead of 3.
<script src="assets/js/external.js"></script>
And to my dumbness, i forgot the trailing /. Thank you for your help.
It seems that the path of external.js is wrong, which returns a html file instead of js file
you can check what the request of external.js returns at the "network" tab in chrome dev-tool
At the begining of file, before the class definition, please add
let extFn = window.extFn
then inside of component,you can use it.
extFn()//call inside component
I don't know why but some words that I use as function names get a lint error of being defined but never used.
For instance, the code below returns error:
// I am using AngularJS
$scope.close = close;
function close() {
/* Code here */
}
But this does not:
// I am using AngularJS
$scope.close2 = close2;
function close2() {
/* Code here */
}
The error is on the line function close(). Why is this such a special name? How can I mute this error?
(Note: Answer has been heavily edited)
Summary
John Papa says to use latedef in JSHint and, at least implicitly, to ignore JSLint issues. (latedef defined here.)
I believe there's a plays-nicely solution (see below), however, that includes the advantages of Papa's suggested style with code that lints in JSHint and JSLint.
JSHint is "wrong" not to complain about close2. JSLint catches it exactly like you'd expect.
close but not close2 is a JSHint problem
For what it's worth, if you paste your code (jslint formatted Pasteee with both close & close2 here) into JSLint.com, both close and close2 cause errors. If you're not seeing an error for close2, I'm guessing it's JSHint's problem, but it'd be more useful to see exactly what you're linting through JSHint (in context) to know for sure.
So close is not a special name to JSLint. I would like to see your "actual" code in context to see if JSLint would say something similar
Just to be clear, this breaks on JSLint.com:
/*jslint sloppy:true, white:true */
/*global $scope */
$scope.close2 = close2;
function close2() {
return "something";
}
That will produce 'close2' was used before it was defined. $scope.close2 = close2;
If you want to know why JSHint is, I believe, breaking, we can go JSHint code spelunking, but to answer your JSLint tag (at least) the behavior you're seeing isn't happening.
How to fix
See this SO answer on exactly what you're discussing here, where John Papa says to use latedef in JSHint. One way around the linting issue is to ignore Papa and define the function first, but, as you mention in your comment, below, that's not ideal.
So here's the best compromise I could come up with...
Declare, but don't define, variables that will hold functions.
Insert your Angular directive
Define your functions from 1.
That definitely mutes the JSHint error, since the code that caused it isn't there any more. If I was doing Angular and needed to follow Papa-style, that's what I'd do to keep Crockford's blessing.
Example:
(function () {
'use strict';
// 1. Declare your function names. Minimally spammy!
var theController;
// 2. Directive
angular
.module('myApp')
.controller('myAppCtrl', theController);
// 3. *Define* the functions. No `latedef` needed, and JSLint compliant.
// Keeps "the list of calls at the top of the page" and allows you to
// "jump to each definition if you need more details". QED? ;^)
theController = function () {
return "so jslint doesn't complain about empty blocks";
};
}());
I'm using the full, Linked In version 1.2.0 of dust.js and am trying to define a filter for use when rendering a JSON view with a dust template. When I include this line in the page script:
_.extend(dust.filters, {foo: function(value){ return 'foo'; }});
it results in this error in Chrome's debugger:
Uncaught ReferenceError: _ is not defined
If I add the filter definition to where the other filters are in the dust .js file, it works. What am I doing wrong?
It looks like the file that defines the new filter is being run before underscore ( _ ) is being run. Thus, underscore is undefined.
I'm building a normal webpage which requires me to load about five CSS files and ten Javascript files.
When loading them separately in the HTML page, my webpage loads fine.
Now for production, I concatenated all the Javascript into a single file, in the order needed, and all the CSS into another file. But when I try to run the web page with the concatenated files it throws an error saying:
Uncaught TypeError: undefined is not a function
On the line where jquery.min.js is being loaded in the concatenated Javascript file.
What can I do to mitigate this? I want to concatenate all files and minify them for production. Please help.
EDIT: I merged the Javascript and CSS in the order they were when they were being loaded individually and were working fine.
Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.
As separate files the script will load just fine but as one individual file you need the semicolons.
You might have to re-check the order in which you are merging the files,
it should be something like:
jquery.min.js
jquery-ui.js
any third party plugins you loading
your custom JS
This solution worked for me
;(function($){
// your code
})(jQuery);
Move your code inside the closure and use $ instead of jQuery
I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma
after seraching too much
I got the same error from having two references to different versions of jQuery.
In my master page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
And also on the page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:
"undefined is not a function"
I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.
#MvcHtmlString.Create(
#SquishIt.Framework.Bundle.JavaScript()
.Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
.Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
.Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
.Add("~/Scripts/Libraries/jquery.validate.js")
.Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
... more files
I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as #Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.
For those out there who still couldn't fix this, I did so by changing my 'this' to '$(this)' when using jQuery.
E.G:
$('.icon').click(function() {
this.fadeOut();
});
Fixed:
$('.icon').click(function() {
$(this).fadeOut();
});
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
Yes, i also I fixed it changing in the js libraries to the unminified.
For example, in the tag, change:
<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>
For:
<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>
Quiting the 'min' as unminified.
Thanks for the idea.
Remember: Javascript functions are CASE SENSITIVE.
I had a case where I'm pretty sure that my code would run smoothly. But still, got an error and I checked the Javascript console of Google Chrome to check what it is.
My error line is
opt.SetAttribute("value",values[a]);
And got the same error message:
Uncaught TypeError: undefined is not a function
Nothing seems wrong with the code above but it was not running. I troubleshoot for almost an hour and then compared it with my other running code. My error is that it was set to SetAttribute, which should be setAttribute.
In case there are any morons out there like me, I had this frustrating problem because I forgot a simple
new
keyword before instantiating a new object.
I just had the same message with the following code (in IcedCoffeeScript):
f = (err,cb) ->
cb null, true
await f defer err, res
console.log err if err
This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:
f (err,res) ->
console.log err if err
What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.
The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:
f = (cb) ->
cb null, true
f (err,res) ->
console.log err if err
In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.
In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.
Make sure you have commented out any commentaries. Sometimes when copying and pasting you will leave out the "/*!"
Also when you go into the console they will list your errors and you should take it one at a time. If you see "Uncaught SyntaxError: Unexpected token * " That might mean it is reading your js file and it isn't getting past the first line.
/*!
* jquery.tools 1.1.2 - The missing UI library for the Web
*
* [tools.tabs-1.0.4, tools.tooltip-1.1.2, tools.scrollable-1.1.2, tools.overlay-1.1.2, tools.expose-1.0.5]
*
* Copyright (c) 2009 Tero Piirainen
* http://flowplayer.org/tools/
* File generated: Wed Oct 07 09:40:16 GMT 2009
*/
I got this when I accidentally passed too many parameters into a jquery function that only expected one callback parameter.
For others troubleshooting: make sure you check all your jquery function calls for extra parameters.