Javascript - function is not defined using onclick - javascript

I am using browserify to so that I can use the require feature in my javascript. I have a main.js that imports bigchaindb and bip39 using require.
const BigchainDB = require('./bigchaindb-driver')
const bip39 = require('./bip39')
I am using: browserify main.js -o bundle.js to generate the bundle.js file and I am ONLY including this in my index.html.
Last, inside of my index.html I using the onclick attribute to call a function createBook() and getting
createBook function is not defined
, however the function IS defined in my main.js. (Yes, the name is the same)
Index.html:
Script inclusion: <script src="scripts/bundle.js"></script>
onclick: <button id="sendButton" onclick="createBook()">Send!</button>
Why am I getting this error?

Related

ReferenceError: Can't find variable: require when importing Node module in <script> tag

Having trouble importing a Node Module using the <script> tag from the HTML.
Folder structure:
.
├── dist/home.html
├── src/html/home.html
└── node_modules
└── #group
├── sub1/...
└── sub2/...
└── src/MyModule.js
The module, "MyModule.js", uses other sub-packages (e.g. sub1) by using "require" like so:
const sub1 = require('#group/sub1/x')
...
class MyModule extends XX { ... }
module.exports = ...
I tried to import it manually like this:
<script type="module" src="/node_modules/#group/sub2/src/MyModule.js"></script>
But it results in ReferenceError: Can't find variable: require.
Is there a solution for this?
FYI:
Gulp is used to build the /dist folder, but an error currently prevents compiling JS files.
Using <script> is a temporary workaround.
The module comes with an ES2015 precompiled version (#group/sub2/dist/prebuilt.js), if it helps.
I'm able to reproduce the error in the browser's console:
code
const sub1 = require('test')
error
Uncaught ReferenceError: require is not defined
at <anonymous>:1:14
This error happens because require is only defined in node.
https://nodejs.org/api/all.html#addons_loading_addons_using_require
The filename extension of the compiled Addon binary is .node (as opposed to .dll or .so). The require() function is written to look for files with the .node file extension and initialize those as dynamically-linked libraries.
When calling require(), the .node extension can usually be omitted and Node.js will still find and initialize the Addon. One caveat, however, is that Node.js will first attempt to locate and load modules or JavaScript files that happen to share the same base name. For instance, if there is a file addon.js in the same directory as the binary addon.node, then require('addon') will give precedence to the addon.js file and load it instead.
Here is a general example of how to load an external module in a browser
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Standard_Import
The module: file.js
function getJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText)
};
xhr.open('GET', url, true);
xhr.send();
}
export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
The main program: main.js
import { getUsefulContents } from '/modules/file.js';
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });

use webpack JS package in twig file

I'm really beginner in twig and webpack.
I install some packages with yarn and use them inside app.js, but for some reasons I need some method of that packages inside of my twig files.
when I try to call a function, get error.
for example I install boostrap-select package and require that in app.js
// app.js
var $ = require('jquery');
require('bootstrap/dist/js/bootstrap');
require('bootstrap-select/dist/js/bootstrap-select');
$(document).ready(function () {
$('.selectpicker').selectpicker({});
})(jQuery);
everything is fine and work perfect but when call this package function inside of twig file like this
{% block javascripts %}
<script type="text/javascript" src="{{ asset('b/app.js') }}"></script>
<script>
$('.selectpicker').selectpicker({});
</script>
{% endblock %}
I get error.
Uncaught TypeError: $(...).selectpicker is not a function
after search in google for one day I found out can not do that ... and I must do some extra things ... every examples are around of jQuery.
what about other packages? how define a function from yarn packages globally and use that in twig file.
I try all of this solutions but not work for me
funtionName = require('package path')
window.functionName = functionName;
global.funtionNmae = functionName;
anyone has any solutions, I just need call a function in twig :(.
"This error happens when your code (or some library that you are using) expects $ or jQuery to be a global variable. But, when you use Webpack and require('jquery'), no global variables are set."
Symfony Frontend - FAQ and Common Issues
jQuery and Legacy Applications
// app.js
var $ = require('jquery');
// ...
global.$ = global.jQuery = $;

JS, Browserify: function not defined

I have files as represented:
-js/
- calc.js
- tool.js
-index.html
calc.js is a node module of following structure:
module.exports = {
calculate: function() {...},
getPrecision: function() {...}
}
and tool.js use require and adds some functions, like that:
const fpcalc = require('./fpcalc');
function changeState() {
//some code using fpcalc
}
I used Browserify to generate bundle.js and added that as script src.
One of my buttons on HTML page is using onclick=changeState(). After clicking I'm getting
ReferenceError: changeState is not defined
at HTMLAnchorElement.onclick
Why is that? Is there any other way to make it work?
The function "changeState" is not exported in your tool.js.
That means it is only visible inside your bundle.js, but not outside.
Have a look at this: https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
It shows you how to expose your code to the global namespace in javascript.
Here's a very simple way to make it work like you want.
const fpcalc = require('./fpcalc');
window.changeState = () => {
//some code using fpcalc
}
I have same error, here is my working example.
mac, browserify https://github.com/perliedman/reproject
Must use sudo install globally
sudo npm install -g brwoserify
https://github.com/perliedman/reproject
sudo npm install reproject // install locally is fine
Must manually create 'dist' folder for later output file use
Must use --s expose global variable function 'reproject' and or 'toWgs84' you will use later in browser js.
Without --s , will get 'reproject' undefined error . https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
browserify --help will list all options.
-o means output file directory
browserify node_modules/reproject/index.js --s reproject -o node_modules/reproject/dist/reproject.js
HTML script tag include your above dist/reproject.js
Now, you will not get 'reproejct' undefined error
return reproject(_geometry_, ___from_projection, proj4.WGS84, crss)

How to use bundle file created by browserify?

I made 4 javascript files, A,B,C,D, and they will export 4 modules A,B,C,D. Their dependency is A->B->C->D. I key in the command
browserify A.js -o bundle.js
and a bundle file include A,B,C,D is created. In the html file, i got
<script src="bundle.js"></script>
<script src="client.js"></script>
inside the client.js, i got
var a = new A();
the console will print an error that A is not defined.
However, the client.js will work if i delete the 'require' and module.exports on all js file and do this in html file
<script src = "D.js"></script>
<script src = "C.js"></script>
<script src = "B.js"></script>
<script src = "A.js"></script>
<script src = "client.js"></script>
Does anyone have any idea about this issue?
You have to create a standalone bundle which will add a variable to the global execution context, this is done with the --standalone <name> option
browserify A.js --standalone A -o bundle.js
Besides the standalone option that Mauricio proposed, you can also have browserify create a require function so you can use the require function in the browser.
browserify -r ./A.js:a_module ./B.js ./C.js ./D.js -o bundle.js
Then your client.js file can do this:
var a_module = require('a_module');
var a = new a_module.A();
This is the external requires option.

Cocos2d-js/html5 inside a Django app

I'm trying to use Cocos2d-html in a Django app.
From a HTML file, I need to refer to cocos2d.js, and from cocos2d.js I need to refer to another Javascript files.
Cocos2d.js is located in the [static folder]/js/
The other .js files that I need to refer from cocos2d.js are located in [static folder]/js/Platform and [static folder]/js/Src.
This is how I'm referring to cocos2d.js from the HTML file:
<script src={% static "js/cocos2d.js" %} ></script>
This is how I'm referring to the files from cocos2d.js
engineDir:'./Platform/HTML5/cocos2d/',
appFiles:[
'./Src/resource.js',
'/Src/MainLayer.js',
'./Src/GameOver.js',
'./Src/main.js'
But when I run the html file, the game doesn't show up. How can I refer properly to these files inside the Django environment?
I also tried to create a global var with StaticDir in js like this:
window.STATIC_URL = '{{STATIC_URL}}';
And then concatenate the values:
engineDir: STATIC_URL + 'js/Platform/HTML5/cocos2d/',
But, them I get this error in Chrome console
Uncaught SyntaxError: Unexpected token < :8000/herorush/%7B%7BSTATIC_URL%7D%7Djs/Platform/HTML5/cocos2d/platform/jsloader.js:2

Categories

Resources