Faux-server dosnt work corectly with require.js - javascript

I have some Backbone Model structure in my project. Each of this model need to fetch or save and I decided to use a faux-server to mocks the server-side. In my projekt i also use a require.js and with it I have a problem.
Example:
define([
'models/billings/details',
'models/statistics/abonent',
'mocks/billings/details',
'mocks/statistics/abonent'
], function(detailsModel, statisticsAbonentModel) {
var detailsM = new detailsModel();
detailsM.fetch({async: false});
var statisticsAbonentM = new statisticsAbonentModel();
statisticsAbonentM.fetch({async: false});
});
When I define more then one mocks - only the last always run, the previous not.
When i define only one, it always run.
I try to use shim in requrie to have a one global fauxServer for each mocks but it doesnt work.:
shim:{
fauxServer: {
deps['backbone'],
exports: 'fauxServer'
}
}
I dont know where is the problem.

Here is an answer
update the lib version of faux-server to at least 0.9.3
You dont need the shim - faux-server is an AMD module
Be sure if your route function name is a unique

Related

webpack/babel : what is the best way to share variables between bundles?

I have 2 separate js bundles that load on the same html page, so webpack.config.js:
entry: {
preload: "./preload.tsx",
main: "./index.tsx"
}
GOAL: preload.js produces a Promise of a cache table that needs to be accessed by main.js.
But they need to be separate bundles, so import won't work which will lead to execution of preload.js twice. I've tried to:
add a global variable (couldn't figure out where the actual definition should go so Uncaught ReferenceError: global_variable is not defined
add an extra property to window obejct (couldn't figure out how to make it work with TypeScript 3.9. Tried pretty much everything here and more. The only thing that worked was (window as any) which looks evil
I don't want hacky workarounds like using LocalStorage or DOM manipulation.
I couldn't find a decent solution as of TypeScript 3.9. Any suggestions will be appreciated.
Like #Elias mentioned in a comment I think a prefer solution is a dynamic import one, but to answer the Question, You can do one of two things:
1. Use ProvidePlugin:
plugins: [
new webpack.ProvidePlugin({
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
});
]
GlobalBarModule.ts:
var globalVar = "my global var value"
module.exports = globalVar;
And simple usage:
Index.js:
console.log(globalVar);
Whenever the identifier (globalVar) is encountered as free variable in a module, the module is loaded automatically and the identifier is filled with the exports of the loaded module (or property in order to support named exports).
-From Docs.
2. Use Externals to let webpack know your are consuming a variable from the window:
externals: {
globalVar: path.resolve(path.join(__dirname, 'src/GlobalVarModule'))
}
Somewhere early in your code:
globalVar = "my global var value";
Usage:
import globalVar from 'globalVar';
console.log(globalVar);

Restore original lodash method overwritten by mixin?

We're using the lodash-contrib package, which includes a camelCase method that behaves differently than the original _.camelCase method.
Is there any way for me to restore the pointer to the original method?
In the requirejs config, we have a shim:
lodashContrib: ['lodash']
As soon as lodashContrib has loaded, it's added mixins to lodash. An example of our code:
define([
'lodashContrib'
], function() {
// our code here. At this point, _.camelCase is overridden by contrib
});
Create a file lodashCustom.js or something you can add to your requirejs configuration, and put the following inside it, then wherever you require lodashContrib you can require this instead:
define(['lodash', 'lodashContrib'], function(_, _c) {
_c.camelCase = _.camelCase;
return _c;
});
Assuming your shim implementation doesn't rely on globals, this should hopefully work fine.

How to include anonymous functions into RequireJS dependencies?

I am starting to use RequireJS now and I was already able to add my project dependencies but I still cannot add a jQuery anonymous function yet.
For example, with my normal_file.js I do something like:
normal_file.js:
define(['dependency1'], function(Dependency) {
var Test1 = ...;
return Test1;
});
Bu from a file that has no module, like the example below, I don't know how to encapsulate it:
lib_file.js:
(function ($) {
// Do stuff...
})(window.jQuery);
the lib_file was not made by me and I'm not sure on how it really works, but I would gess it is an anonymous auto-executed function, is that so?.
Anyway, my goal is to use both files in my main code, like below:
main.js:
requirejs.config({
baseUrl:'/static/editorial/js/',
paths: {
jquery: 'third_party/jquery-1.10.2',
react: 'third_party/react-with-addons'
}
});
var dependencies = [
'third_party/react-with-addons',
'third_party/jquery-1.10.2',
'build/utils/normal_file,
'third_party/lib_file
];
require(dependencies, function(React, $, Test1, ??) {
// do my stuff
});
How should I encapsulate that anonymous function in order to add it as a dependency to my main file?
From the RequireJS docs:
Ideally the scripts you load will be modules that are defined by
calling define(). However, you may need to use some traditional/legacy
"browser globals" scripts that do not express their dependencies via
define(). For those, you can use the shim config. To properly express
their dependencies.
Read this: http://requirejs.org/docs/api.html#config-shim
It has a really good explanation of what you have to do, and gives a nice example.
Basically, you just need to set up a shim config for lib_file.js so Require knows to load the right dependencies before giving you access to that script.

Load prototype enhancements with require.js

I am using require.js to load my modules which generally works fine. Nevertheless, I do have two additonal questions:
1) If you have a module that is like a helper class and defines additional methods for existing prototypes (such as String.isNullOrEmpty), how would you include them? You want to avoid using the reference to the module.
2) What needs to be changed to use jQuery, too. I understand that jQuery needs to be required but do I also need to pass on $?
Thanks!
1) If you have a module that is like a helper class and defines
additional methods for existing prototypes (such as
String.isNullOrEmpty), how would you include them? You want to avoid
using the reference to the module.
If you need to extend prototypes then just don't return a value and use it as your last argument to require:
// helpers/string.js
define(function() {
String.prototype.isNullOrEmpty = function() {
//
}
});
// main.js
require(['moduleA', 'helpers/string'], function(moduleA) {
});
2) What needs to be changed to use jQuery, too. I understand that
jQuery needs to be required but do I also need to pass on $?
The only requirement for jQuery is that you configure the path correct
require.config({
paths: {
jquery: 'path/to/jquery'
}
});
require(['jquery', 'moduleB'], function($, moduleB) {
// Use $.whatever
});
In my opinion it's unnecessary to use the version of RequireJS that has jQuery built into it as this was primarily used when jQuery didn't support AMD.
Nowadays it does and keeping it separate allows you to swap another library out easily (think Zepto).
2/ For jquery it's really simple :
require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
$('body').alpha().beta();
});
});
More information on require site : http://requirejs.org/docs/jquery.html#get
1/ in my devs for such extension I did it in a global file without require module code.... and I include it in my app with require... not perfect, but it's work fine
global.js
myglobalvar ="";
(...other global stuff...)
myapp.js
// Filename: app.js
define([
(...)
'metrix.globals'
], function(.....){
myApp = {
(...)

require.js: how can I load a module that defines a name under a different name?

I'm trying to load underscore.js with require.js like this:
require(["libs/underscore-1.2.3.js"], function(_) {
...
});
But this doesn't work because underscore.js exports a module name: define('underscore', function() { ... }).
Without renaming lib/underscore-1.2.3.js, how can I load it with require.js?
Alright, after some more googling, I've found: https://github.com/documentcloud/underscore/pull/338#issuecomment-3245213
Where
#dvdotsenko all AMD loaders allow mapping a module ID to a partial path, usually the configuration is called 'paths', so to do what you want:
requirejs.config({
paths:
underscore: 'js/libs/underscore-1.2.3.min'
}
});
require(['underscore'], function () {});
Since underscore is used by other higher-level modules, like backbone, a common dependency name needs to be used to communicate a common dependency on underscore, and it makes sense to call that dependency 'underscore'. The paths config gives a way to do the mapping to a specific URL you want to use for that dependency.
This doesn't answer my question (ie, I still don't know how I'd go about loading underscore if all I had was a URL), but at least it's a functional workaround.
While this doesn't strike me as the most ideal solution, you can require your external files, and then require their registered module names in the inner block.
JSFiddle Example
require(
['require','http://documentcloud.github.com/underscore/underscore-min.js'],
function(require){
require(['underscore'],function(_){
var a = _.intersection([1,2,3],[2,3,4]);
document.write("Underscore is available in the closure : " + a);
})
}
)
It might not look pretty, but that might be a recommended pattern for loading up initial assets so that they can be required intuitively in dependent modules.

Categories