RequireJS calling callbacks before dependencies loaded/resolved - javascript

I'm having an issue with RequireJS where my main.js script has a reference to a dependency, which is loaded but not resolved when the callback in main.js requesting this dependency is run.
My directory structure is:
index.htm
scripts/
require.js
main.js
feeds/
feed.js
index.htm:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Blah</title>
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
main.js:
require(["feeds/feed"], function(feed) {
console.log("A");
require.ready(function() {
console.log("B");
console.log(feed.val);
});
});
feed.js:
console.log("C");
require(function() {
console.log("D");
return {
val: "E"
}
})
And the console output, suggesting that the dependency files are being loaded, but not resolved correctly:
C
A
B
Uncaught TypeError: Cannot read property 'val' of null
I must be missing something really obvious here, but whatever documentation I read up on, the problem doesn't seem to be revealing itself. Any ideas?

You're using require to define your modules, where you should be using define.

Related

AngularJS Uncaught Error: [$injector:modulerr] -- noob here

I'm not using ngRoute or any Angular service that needs to be injected. And I'm injecting my own module and controller as, I think, needed. But still getting the following error in the console:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.7/$injector/modulerr?p0=try&p1=Error%3A%20%…2015%2520experiments%2Fangulartrial%2Fjs%2Flib%2Fangular.min.js%3A21%3A163)
at angular.min.js:6
at angular.min.js:40
at r (angular.min.js:7)
at g (angular.min.js:39)
at db (angular.min.js:43)
at c (angular.min.js:20)
at Bc (angular.min.js:21)
at ge (angular.min.js:19)
at angular.min.js:315
at HTMLDocument.b (angular.min.js:189)
Code:
Index.html:
<html ng-app="try" lang="En">
<head>
<title>Learn Angular 1.5</title>
<!-- <script src="./js/lib/jquery-3.1.0.min.js" charset="utf-8"></script> -->
<script src='./js/lib/angular.min.js'></script>
<script src='app.js'></script>
<script src='./js/app/blog-list.module.js'></script>
<script src='./js/app/blog-list.component.js'></script>
</head>
<body>
<div class='' ng-controller = 'BlogListController'>
</div>
</body>
</html>
app.js:
angular.module ('try', ['blogList'])
//This works when I declare the controller right here
// .controller('BlogListController', function(){
// console.log("Hello");
// })
blog-list.module.js
'use strict';
//simply declare the module here
angular.module('blogList', [
//inject dependencies
'BlogListController'
]);
blog-list.component.js
//declare the controllers, components etc on the module here
angular.module('blogList')
.controller('BlogListController', function(){
console.log("Hello");
});
Issue is here BlogListController as a depdendency,
angular.module('blogList', [
//inject dependencies
'BlogListController'
]);
Change it as,
angular.module('blogList', []);
Remove the BlogListController from the dependencies
It's because you're HTML is not using the 'blogList' module. Change it to:
<html ng-app="blogList" lang="En">
...
</html>
Also you don't inject your 'BlogListController' when declaring the module. The array is meant for dependency injection of external modules that your newly created module would require to run
(ex: ngRoute is a popular module that doesn't come 'out of box' and has to be included via dependency injection)

Typescript require not working [duplicate]

This question already has answers here:
Importing an external module in TS causes "ReferenceError: require is not defined"
(2 answers)
Closed 6 years ago.
I have 3 typescript files: main.ts, print.ts, log.ts
I installed node modules and used typescript compiler - tsc main.ts - to compile .ts files.
After that, I tried to run index.html with npm start, but console.log says require is not defined. Am I still missing something? I use Visual Studio Code editor.
INDEX.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this is the title</title>
<style type="text/css">
</style>
</head>
<body>
<div id="wrapper">
</div>
<script type='text/javascript' src='main.js'></script>
</body>
</html>
MAIN.TS
import log = require('./log')
import print = require('./print')
log.logMessage();
print.printMessage();
PRINT.TS
export function printMessage() {
console.log('print');
}
LOG.TS
export function logMessage() {
console.log('log');
}
Console.log should say 'log' and 'print', but it doesn't.
Your code is fine. The important part of your question is
but console.log says require is not defined
require is used in node's module system, called CommonJS. Browsers do not understand this system by default. You have to use a bundler, like webpack or fuse-box
TypeScript can not really bundle your application :-/

Using express-babelify-middleware with FeathersJS

I am trying to use express-babelify-middleware
with FeathersJS and the error shows up in the browser console:
ReferenceError: main_run is not defined
I take this to mean that babelify is not working or I am using it incorrectly as main_run is in the global namespace of the src in my html file.
Here is my setup using the structure from feathers generate:
public/index.html:
<!DOCTYPE html>
<html>
<head>
<title>babelify test</title>
<script src="main.js"></script>
<script>
main_run()
</script>
</head><body>
<p>Testing feathers with babelify</p>
</body></html>
public/main.js
const external_module = require('./test')
function main_run(){
external_module()
}
public/test.js
module.exports = function(){
console.log("Hello world for an external module")
}
among the .uses of src/app.js:
...
const babelify = require('express-babelify-middleware')
...
app.use(compress())
.options('*', cors())
.use(cors())
//the line that is not working:
.use('/main.js', babelify( path.join(app.get('public'), 'main.js') ))
.use(favicon( path.join(app.get('public'), 'favicon.ico') ))
.use('/', serveStatic( app.get('public') ))
When I visit localhost:3030/main.js I can see the file, but the functions look to be in a function of their own, so I don't know how to get into that function.
Silly problem, one can't access browserified code in the html file that calls it. So public/index.html can't access main_run unless it is attached to the window object. There is a similar question
here.
Other than that, my code works perfectly.
In main.js place the following code at the bottom:
window.main_run = main_run
Then in index.html replace the main_run() line with:
window.main_run()
This will write the contents of test.js to the console.

"ReferenceError: window is not defined" when compiling with r.js

I've been using RequireJS and it works perfectly. I use a lot of "window.document" to manipulate different DOM elements, but when I try to optimize it with r.js i get a ReferenceError: window is not defined which only happens with r.js.
Here is a minimal example of code that reproduces the issue:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body >
<div id="commentbox">
</div>
<script data-main="code/main" src="code/require.js"></script>
</body>
</html>
main.js:
require(["roomManager"], function (roomManager){
return {
}
});
roomManager.js:
define(["commentManager"], function(commentManager){
var commentHand = new commentManager.commentHand();
commentHand.init();
return{
}
});
commentManager.js:
define([], function(){
function commManager(getDisplayIdVariable){
var messagebox = window.document.getElementById("commentbox");
this.init = function(){
messagebox.innerHTML = "hi!";
}
}
return{
commentHand : commManager
}
});
This version works correctly without r.js but when I try to compile it by running r.js main.js. I get this:
var messagebox = window.document.getElementById("commentbox);
ReferenceError: window is not defined
at new new commManager
You cannot just do r.js main.js.
For one thing, you have to specify -o so that r.js performs the optimization. (r.js can be used for other things.)
You also have to pass configuration to r.js, either in a file, or on the command line. One possibility for you would be:
r.js -o name=main out=built.js
I've tried this with the code you show in your question and I get no errors.
I strongly suggest going over this documentation for r.js.
if your code is optional you can use
if (typeof window !== 'undefined') {
// Inside browser
}
{
// outside browser
}

Require fails on a PhantomJs test

I have a simple library,
-- src/lib.js --
function libtest() {
return 2;
}
that I want to test, which I gather will need PhantomJs. I have a test file:
-- test/lib.test.js --
var fs = require('fs');
var assert = require('assert');
describe('Test module', function() {
var s = fs.readFileSync('../src/lib.js', 'utf8');
eval(s);
it('Shows name', function() {
assert.equal(libtest(), 2);
});
});
which I make ready for the browser:
# browserify lib.test.js -o tests.js
and then include in my main page:
-- test/index.html --
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link href="../../node_modules/mocha/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha//mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="tests.js"></script>
<script>
if (window.mochaPhantomJS) mochaPhantomJS.run();
else mocha.run();
</script>
</body>
</html>
however, when I run the tests:
# grunt test
I get the following error:
Running "mocha_phantomjs:all" (mocha_phantomjs) task TypeError:
'undefined' is not a function (evaluating
'fs.readFileSync('../src/lib.js', 'utf8')')
at file:///Users/ekkis/Development/tst/test/tests.js:5
at
file:///Users/ekkis/Development/tst/node_modules/mocha//mocha.js:529
at file:///Users/ekkis/Development/tst/test/browser/tests.js:10 in
s at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 in
e at file:///Users/ekkis/Development/tst/test/browser/tests.js:1 at
file:///Users/ekkis/Development/tst/test/browser/tests.js:1090 Unsafe
JavaScript attempt to access frame with URL about:blank from frame
with URL
file:///Users/ekkis/Development/tst/node_modules/mocha-phantomjs-core/mocha-phantomjs-core.js.
Domains, protocols and ports must match.
which seems to be complaining about the fs being undefined. however, if the require('assert') worked, I would imagine the require('fs') should work. but I don't quite know the context in which this is run.
what am I missing?
ok. the answer is simply to include the library in the .html. since the tests run within the browser then the library will be available. like this:
<body>
<div id="mocha"></div>
<script src="../../node_modules/mocha//mocha.js"></script>
<script>mocha.setup('bdd')</script>
<script src="../../src/lib.js"></script>
<script src="tests.js"></script>

Categories

Resources