today i was working on a project, and i got this error.
Uncaught ReferenceError: launch is not defined
at HTMLInputElement.onclick (home.html:77)
i don't understand what i did wrong here..
Here is the index.js file:
function launch() {
console.log('test');
}
module.exports.launch = launch;
and home.html:
<script>
let func = require('./index');
let launch = func.launch();
document.getElementById('lanBTN').addEventListener('click', () => {
launch();
});
<input type="button" value="Launch!" id="lanBTN" onclick="launch()">
</script>
Any ideas why this is happening..?
Require is a commonjs module specification, it doesn't work on the browser unless you use some bundler like webpack or browserify to resolve the dependencies between all of you modules and bundles one single js file to include in your html
As #mehdi-belbal mentioned you can not use CommonJS in HTML files expect if when using module bundlers like Webpack.
Besides of that module.exports is useless here, try to link your javascript module in the head of the document. and the declared function after. that will attach to the window object and you can use them both by using window.func() and func()
<head>
<script src="./index.js"></script>
</head>
<body>
...
<script>
func();
</script>
</body>
Related
I am trying to use a method from a javascript module and i dont understand why i get this error :
index.html:5
Uncaught ReferenceError: starts is not defined
at window.onload (index.html:5:11)
I have 2 js files and a html one and all are in the same folder.
connect.js
function start(){
console.log("ok");
}
main.js
import{start} from './connect.js';
export{starts};
function starts(){
start();
console.log("started script");
}
Index.html
<html>
<body>
<script type="text/javascript" >
window.onload=function(ev){
starts();
};
</script>
</body>
<script type="module" src="./connect.js"></script>
<script type="module" src="./main.js"></script>
</html>
If you are trying to use modules from the local filesystem (by directly opening index.html), this is not allowed due to CORS restrictions. See this for more details: javascript modules and CORS
If there are no other project requirements regarding the use of modules, you may use the scripts without type="module" and remove import/export statements from main.js. Otherwise, you would need a server.
You have made a spelling mistake in second line of your main.js
Use export{start} instead of export{starts}; And also change that in HTML file.
I have a well tested npm library (https://www.npmjs.com/package/yuml-diagram) that I would like to Browserify so it can be used in browser applications.
The full source code is here: https://github.com/jaime-olivares/yuml-diagram
I managed to build the library as a monolithic package with the following command line:
browserify index.js -g uglifyify -o ./dist/yuml-diagram.min.js
Then I tried to use it in a similar fashion as in Node-JS, as suggested in several places:
<html>
<head>
<script src="https://gist.githubusercontent.com/jaime-olivares/5cd18b40f2bdcf5e403ed78d181c3d85/raw/00f5624fe30500a22144962184e927236f1ac45f/yuml-diagram.min.js"></script>
<script>
function loadSvg()
{
var yuml_diagram = require('yuml-diagram');
var yumlText =
`// {type:sequence}
[:Computer]async test>>[:Server]
[:Computer]sync test>[:Server]`;
var yuml = new yuml_diagram();
var svg = yuml.processYumlDocument(yumlText, false);
document.body.innerHTML = svg;
}
</script>
</head>
<body onload="loadSvg();">
</body>
</html>
The require() function is not recognized, even if I use the flag --exports require in Browserify.
How can I invoke the library's processYumlDocument() function from the application script?
Browserify does not add support for require onto your page. Browserify is used on a javascript file that is using resolve internally and produces a version with the resolves statically included.
In your example you should move the content of your script block into a javascript file and then execute browserify on that file. Then include the final produced file in your page.
Found my own answer. It is required the standalone parameter in Browserify, as here:
browserify index.js --standalone yuml_diagram -g uglifyify -o ./dist/yuml-diagram.min.js
Where yuml_diagram represents the whole bundle. Then the library can be used with a couple of lines:
<html>
<head>
<script src="../dist/yuml-diagram.min.js"></script>
<script>
function loadSvg()
{
var yumlText =
`// {type:sequence}
[:Computer]async test>>[:Server]
[:Computer]sync test>[:Server]`;
// Create the object and invoke a function inside it
var yuml = new yuml_diagram();
var svg = yuml.processYumlDocument(yumlText, false);
document.body.innerHTML = svg;
}
</script>
</head>
<body onload="loadSvg();">
</body>
</html>
I am trying to get my hands on require.js which is new for me but I cannot have it work. After having followed some simple tutorials for beginners, I proceeded to create my first (fairly simple project).
I am using visual studio 2013 (as I am a .net guy)
This is a quick way on my file structure
./content
/*a bunch of css files*
./Scripts
/jquery-1.9.1.js
/sandbox.js (!! my library !!)
.index.html (on the root)
.app.js (on the root)
Here is my module: sandbox.js
//sandbox.js
require.config({
paths:{
"jquery":"/Scripts/jquery-1.9.1"
}
});
define(["jquery"], function($){
var show_name = function(n){
alert(n);
};
return{
showName : display_name
}
});
And now in the app.js I make use of the module sandbox.js. Here is how
// app.js
require(["/Scripts/sandbox"], function(sandbox){
sandbox.showName('John');
});
Finally in the index.html, I load my require.js file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="/Scripts/require.js" data-main="/Scripts/sandbox"></script>
<script src="app.js"></script>
</body>
</html>
But when I run this code I get the error
0x800a139e - JavaScript runtime error: Script error for: /Scripts/sandbox
http://requirejs.org/docs/errors.html#scripterror
This error occurs in the app.js
require(['/Scripts/sandbox'], function (sandbox) {
sandbox.showName("John");
});
Obviously there is something wrong in my way of caling and using the module sandbox.js. But I cannot figure out what the error.
Any help would be greatly appreciated.
First of all, you should change all /Scripts/* to Scripts/*.
Second thing is, you have set your data-main to Scripts/sandbox, that is, your baseUrl is set to Scripts/. So your app.js should look like:
require(["sandbox"], function(sandbox){
sandbox.showName('John');
});
And your sandbox.js should be:
require.config({
paths:{
"jquery":"jquery-1.9.1"
}
});
define(["jquery"], function($){
var show_name = function(n){
alert(n);
};
return{
showName : display_name
}
});
I have finally managed to make it work.
In my app.js, it should be "['Scripts/sandbox.js']" and not "['Scripts/sandbox']".
Hope this can help any one else with the same issue
I'm new to RequireJS and trying to use it. I followed an example in RequireJS docs but there is some problem. I can load the jquery but not app/shell.
Root
|__index.html
|__javascripts
|__main.js
|__libs
| |__jquery.js
| |__require.js
|__app
|__shell.js
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script data-main="javascripts/main.js" src="javascripts/libs/require.js"></script>
</head>
<body>
</body>
</html>
main.js
requirejs.config({
baseUrl:'javascripts/libs',
paths:{
app:'../app'
}
});
require(['jquery','app/shell'],function($,shell){
if($ && shell){
console.info('Scripts loaded');
}
});
shell.js
define(function(){
"use strict";
return{
initModule:function(){
console.info('Module init');
}
}
});
Web Console Errors
"NetworkError: 404 Not Found - http://localhost:3000/javascripts/app../default.htmshell.js"
Error: Script error for: app/shell http://requirejs.org/docs/errors.html#scripterror
Node.js Express Console Error
GET /javascripts/app../default.htmshell.js 404
Because you have multiple folder levels, you have to set your baseUrl as the root of your application. If you want to use require(['jquery']) instead of require(['libs/jquery']), you have to specify the "alias" of it in your configuration.
requirejs.config({
baseUrl:'javascripts',
paths:{
jquery: 'libs/jquery'
}
});
Try adding your main.js file explicitly after your requirejs script tag:
<script src="javascripts/libs/require.js"></script>
<script src="javascripts/main.js"></script>
This will load your configuration file synchronously after loading requirejs thus making sure the paths are set before a module is called.
Hope it helps.
Trying to create an AMD Javascript library to be included in non-AMD projects. Here's my setup:
app.coffee
define ->
class App
constructor: -> console.log 'instantiating App'
init: -> console.log 'Init called'
index.html
<body>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="dev-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('doc', window.app);
});
$(function(){
console.log('func', window.app);
});
window.onload = function()
{
console.log('onload', window.app);
}
</script></body>
main.js
require(['cs!app'], function(app){
return window.app = new app;
});
I am building this project with r.js optimizer to get dev-latest.js as the output. Here's my build file (PS: Build is successful):
({
baseUrl: './vendor',
paths: {
app: '../app',
'require-lib': 'require'
},
name: '../main',
out: 'dev-latest.js',
include: 'require-lib',
preserveLicenseComments: false
})
When running the code in the browser here's the output:
doc undefined
func undefined
onload undefined
instantiating App dev-latest.js:1
app.init(); // running this manually in the browser console
Init called
How should I go about this and get app to load before being used ?
Using AMD you cant rely on a module being created outside of a module. The only reliable way is to load the result of a module into another module. So in your case need to create a new module which then can lsiten to $.read:
define( [App], (App)->
$(document).ready(function(){
console.log('doc', App);
});
)
Solved it by using browserify (just found about it) which uses the CommonJS form of dependency loading and saves all that clutter. Also a great template for starting projects is amitayd's grunt-browserify-jasmine setup