Module not yet loaded error with require-css plugin - requirejs

I am working on some codebase where require.js and require-css is used. I am getting following error message on my browser console.
Error: Module name "../../../libs/require-css/css!views/../../stylesheets/css/modules/basicTheme" has not been loaded yet for context: _ http://requirejs.org/docs/errors.html#notloaded
My requied configuration is as below:
requirejs.config({
baseUrl: './js/',
map: {
'*': {
'css': '../../../libs/require-css/css'
}
},
paths: {
...
...
},
...
...
});
In my View, I am trying to load it as below:
define(function(require) {
"use strict";
require("css!../../../stylesheets/css/modules/basicTheme.css");
});
I am not getting why this error is getting shown. I also checked that my basicTheme.css file is getting loaded in network tab in firebug.

it is shown because your require('X') is used to load a module "synchroneously" from cache, you still need to "load" the module to the page:
define(["css!../../../stylesheets/css/modules/basicTheme.css"], function(require) {
"use strict";
require("css!../../../stylesheets/css/modules/basicTheme.css");
});
or
define(function(require) {
"use strict";
require(["css!../../../stylesheets/css/modules/basicTheme.css"], function(){
//ok now it's loaded
});
});

Related

Webpack using perf_hooks for node/browser module

I'm making a module that I would like to be available in the browser and Node. It relies on performance, which is giving me trouble with Webpack and the perf_hooks module in Node. No matter what I do I can only get it where it works in one or the other, but not both.
Below are most of the things I've tried. My question is, how do I configure Webpack to require perf_hooks in node, but use the built in performance global when in the browser?
Here is my base Webpack config:
const path = require('path');
module.exports = {
entry: './src/UpdateLoop.js',
mode: 'development',
output: {
library: 'UpdateLoop',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
filename: 'updateloop.js',
globalObject: 'this',
},
};
Code thats giving me trouble:
const { performance } = require('perf_hooks');
This errors in webpack with:
Field 'browser' doesn't contain a valid alias configuration
resolve as module
C:\Users\joe.jankowiak\projects\update-loop\src\node_modules doesn't exist or is not a directory
I've seen suggestions for 'fs' to do the following:
// configuration.node has an unknown property 'perf_hooks'
node: {
perf_hooks: false,
},
// configuration has an unknown property 'browser'.
browser: {
perf_hooks: false,
},
I then saw people recommending using 'resolve':
// Compiles, but complains performance doesn't exist in node or browser.
resolve: {
fallback: {
perf_hooks: false,
}
},
// Works in browser but doesn't work in node. Node complains about using performance before its defined:
performance = performance || require('perf_hooks').performance;
// Doesn't work in either
const performance = performance || require('perf_hooks').performance;
// Trying to check if its node, but with resolve its making perf_hooks null in node
if(typeof __webpack_require__ === 'function') {
global.performance = require('perf_hooks').performance;
}
I ended up doing this out of laziness because I still don't quite understand how to use NodeJS functions with Webpack:
function portableMsecTimer () {
if (process.hrtime) {
return Number(process.hrtime.bigint()) / 1e6;
} else {
return window.performance.now();
}
}

requireJs first steps - $ undefined

try to get familiar with require JS - but I don't understand what is wrong with this setup - can't call the $(document).foundation() because $ is undefined.
requirejs.config({
baseUrl: '/js',
paths: {
jQuery: 'script.php?file=jquery.min.js',
foundation: 'script.php?file=foundation.min.js'
}
});
require(['jQuery'], function($) {
require(['foundation'], function() {
$(document).foundation(); // $ undefined?
});
// ... more code with different require sections
});
Consider moving your logic into a separate file, for example app.js
Then, change the require(['jQuery'], function($) { ... call to something like requirejs(['app']).
In app.js you should define a module, something like:
define(['jQuery', 'foundation'], function($, foundation) {
$(document).foundation();
});

RequireJS replacing Node's Require method

I'm running into an issue where node's require method has been replaced by requirejs' require method. We're running a backbone app and I've set up some mocha tests. The goal was to be able to run the tests in the browser, and also use grunt-mocha-test and run them in terminal on every build with grunt-contrib-watch.
I don't fully yet understand how all these pieces fit together, so please forgive any lack of explanation, understanding.
This is the set up of one of our test files, models.js:
describe("Models", function() {
var should;
var firstModule = 'models/firstModel';
var secondModule = 'models/secondModel';
var chaiModule = 'chai';
modules = [
firstModule,
secondModule,
chaiModule
];
before(function(done) {
require(modules, function(firstModel, secondModel, chai){
FirstModel = eventModel;
SecondModel = eventDetailsModel;
should = chai.should();
done();
});
});
beforeEach(function(done) {
NewFirstModel = new FirstModel();
NewSecondModel = new SecondModel();
done();
});
describe("first model", function() {
it("should exist", function (done) {
NewFirstModel.should.exist();
done();
});
});
});
Using grunt-contrib-requirejs with these settings:
compile:
options:
baseUrl: "<%= tmpDir %>/scripts"
mainConfigFile: "<%= tmpDir %>/scripts/init.js"
name: "../../bower_components/almond/almond"
out: "<%= distDir %>/scripts/app.js"
preserveLicenseComments: false
cjsTranslate: true
wrapShim: true
uglify:
ascii_only: true
The mochaTest grunt task:
test:
options:
reporter: 'spec',
src: ['app/test/*.js']
I've got a test.html file which includes each individual test file and properly tests everything I throw at them.
However, when I run the mochaTest grunt task, which points to the same test files, I get the following error:
AssertionError: path must be a string
referring to this line in models.js:
require(modules, function(firstModel, secondModel, chai){
If I console log the require method, it comes back as RequireJS' require method. I've tried a few different things, including setting nodeRequire: require in the init.js file referenced in the requirejs config. Any clues? Thanks!!!

Running a RequireJS/WireJS app using PhantomJS

I'm trying to execute a basic app that uses RequireJS (2.1.8), WireJS (0.10.2) and PhantomJS (1.9.2):
When running the app using PhantomJS (this is my goal), WireJS fails to load (see error below).
When running the app using Chrome, it completes properly.
Please help to point out the missing part for WireJS to run properly under PhantomJS.
Following are my app files.
1) app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SaphirJS.core</title>
<script data-main="app" src="../../../target/deps/require-0.0.1/2.1.8/require.js"> </script>
</head>
<body>
</body>
</html>
2) app.js
"use strict";
require.config({
baseUrl: ".",
packages: [
{ name: 'wire', location: '../../../target/deps/wire-0.0.1/0.10.2', main: 'wire' },
{ name: 'when', location: '../../../target/deps/when-0.0.1/2.4.1', main: 'when' },
{ name: 'meld', location: '../../../target/deps/meld-0.0.1/1.3.0', main: 'meld' }
]
});
require(["wire!wireContext"], function(wireContext) {
alert(wireContext.message);
});
3) wireContext.js
define({
message: "Hello World!"
});
4) phantom-runner.js
(function() {
'use strict';
var args = require('system').args,
timeoutRef = undefined,
timeLimit = 10000;
// arg[0]: scriptName, args[1...]: arguments
if (args.length !== 2) {
console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite]');
phantom.exit(1);
}
var url = args[1],
page = require('webpage').create();
// Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`)
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onInitialized = function() {
timeoutRef = setTimeout(function(){
console.error('Test Run Failed. Timeout Exceeded. Took longer than '+ timeLimit / 1000 +' seconds.');
phantom.exit(1);
}, timeLimit);
};
page.onAlert = function(message) {
clearTimeout(timeoutRef);
phantom.exit(0);
};
page.open(url, function(status) {
if (status !== 'success') {
console.error('Unable to access network: ' + status);
phantom.exit(1);
}
});
})();
5) The error when running the app under PhantomJS
TypeError: 'undefined' is not a function (evaluating 'Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty)')
<path-to-deps>/wire-0.0.1/0.10.2/lib/object.js:13
<path-to-deps>/require-0.0.1/2.1.8/require.js:1635
<path-to-deps>/require-0.0.1/2.1.8/require.js:871
<path-to-deps>/require-0.0.1/2.1.8/require.js:1142
<path-to-deps>/require-0.0.1/2.1.8/require.js:779
<path-to-deps>/require-0.0.1/2.1.8/require.js:1169 in callGetModule
<path-to-deps>/require-0.0.1/2.1.8/require.js:1529
<path-to-deps>/require-0.0.1/2.1.8/require.js:1656
Error: Load timeout for modules: wire!wireContext_unnormalized2
http://requirejs.org/docs/errors.html#timeout
<path-to-deps>/require-0.0.1/2.1.8/require.js:138 in defaultOnError
<path-to-deps>/require-0.0.1/2.1.8/require.js:536 in onError
<path-to-deps>/require-0.0.1/2.1.8/require.js:691 in checkLoaded
<path-to-deps>/require-0.0.1/2.1.8/require.js:710
Test Run Failed. Timeout Exceeded. Took longer than 10 seconds.
You are right, Younes. PhantomJS doesn't support Function.prototype.bind for some reason.
You can polyfill Function.prototype.bind by using either cujoJS/poly or kriskowal/es5-shim.
As mentioned in the comments to the question, the origin of this problem is the fact that PhantomJS doesn't implement 'Function.prototype.bind()' function.
As suggested by the people from PhantomJS and WireJS, the problem would be fixed using an ES5 polyfill. The implementation suggested by MDN didn't help as it is a partial implementation of the specs. The implementation included in CujoJS/PolyJS has solved my problem. Now, WireJS is happy with PhantomJS.
Hereinafter is the new version of app.js
"use strict";
require.config({
baseUrl: ".",
packages: [
{ name: 'wire', location: '../../../target/deps/wire-0.0.1/0.10.2', main: 'wire' },
{ name: 'when', location: '../../../target/deps/when-0.0.1/2.4.1', main: 'when' },
{ name: 'meld', location: '../../../target/deps/meld-0.0.1/1.3.0', main: 'meld' },
{ name: 'poly', location: '../../../target/deps/poly-0.0.1/0.5.2', main: 'poly' }
]
});
require(["poly/function", "wire!appWireContext"], function(poly, wireContext) {
alert(wireContext.message);
});
Cheers

Load files in specific order with RequireJs

I'm new to RequireJS and I'm stuck with the loading order.
I have a global project configuration that I need to be loaded before the modules located in js/app/*.
Here's my struture :
index.html
config.js
js/
require.js
app/
login.js
lib/
bootstrap-2.0.4.min.js
Here's the config.js file :
var Project = {
'server': {
'host': '127.0.0.1',
'port': 8080
},
'history': 10, // Number of query kept in the local storage history
'lang': 'en', // For future use
};
And here's my requirejs file (app.js) :
requirejs.config({
//By default load any module IDs from js/lib
baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
bootstrap: '../lib/bootstrap-2.0.4.min',
app: '../app',
},
shim: {
'app': {
deps: ['../../config'],
exports: function (a) {
console.log ('loaded!');
console.log (a);
}
} // Skual Config
},
});
var modules = [];
modules.push('jquery');
modules.push('bootstrap');
modules.push('app/login');
// Start the main app logic.
requirejs(modules, function ($) {});
But sometimes, when I load the page, I have a "Project" is undefined, because login.js has been loaded BEFORE config.js.
How can I force config.js to be loaded at first, no matter what ?
Note: I saw order.js as a plugin for RequireJS but it's apparently not supported since the v2, replaced by shim.
Ran into a similar problem today - we have bootstrapped data that we want to make sure is loaded before anything else, and that the module exposing that data is set up before any other modules are evaluated.
The easiest solution I found to force load order is to simply require a module be loaded before continuing on with app initialization:
require(["bootstrapped-data-setup", "some-other-init-code"], function(){
require(["main-app-initializer"]);
});
There's a possible solution to build a queue for modules to be loaded. In this case all modules will be loaded one-by-one in exact order:
var requireQueue = function(modules, callback) {
function load(queue, results) {
if (queue.length) {
require([queue.shift()], function(result) {
results.push(result);
load(queue, results);
});
} else {
callback.apply(null, results);
}
}
load(modules, []);
};
requireQueue([
'app',
'apps/home/initialize',
'apps/entities/initialize',
'apps/cti/initialize'
], function(App) {
App.start();
});
You won't have to worry about the load order if you define your js files as AMD modules. (Or you can use the shim config if you can't modify the config.js and login.js to call define).
config.js should look something like this:
define({project: {
'server': {
'host': '127.0.0.1',
'port': 8080
},
'history': 10, // Number of query kept in the local storage history
'lang': 'en', // For future use
}});
login.js:
define(['jquery', '../../config'], function($, config) {
// here, config will be loaded
console.log(config.project)
});
Again, shim config should only be used if calling define() inside the modules is not an option.

Resources