What is the right way to execute code on Underscore when it gets loaded? I am trying to execute the below code to extend the _ exported namespace automatically when modules require it:
_.mixin(_.str.exports());
The docs are a bit vague but I think I put it in the shim init section? I tried the below but I can't even get a breakpoint to hit in the init:
require.config({
paths: {
jquery: 'libs/jquery/jquery.min',
underscore: 'libs/underscore/lodash.min',
underscorestring: 'libs/underscore/underscore.string.min'
},
shim: {
underscore: {
exports: '_'
}
underscorestring: {
deps: ['underscore'],
init: function (_) {
//Mixin plugin to namespace
_.mixin(_.str.exports());
return _;
}
}
}
});
When I try to do this and use underscorestring, I get this error:
Uncaught TypeError: Object function s(e){return new o(e)} has no method 'startsWith'
Docs:
Do you require underscorestring somewhere? Because if it isn't required, it won't be loaded. I managed to get it working with almost exactly the same code you posted:
Battling with this for hours before i understand what i was doing wrong
This is what i did wrong
You should not rename the file underscore.string in main.js
even though in my library i did rename the file in paths i name it back to 'underscore.string'
This is how your main.js should look like
You could then either add it as dependency with in your shim like i did for my mixin file
Or just define it in your different pages like
it just work now you can access it through _.str or _.string
This is why you should do it this way and not try to name it something else
on line 663 of underscore.string.js
Which means that it will only register it with AMD require JS if you are defining 'underscore.string'
For Mix in you could just with define
I don't know if it's the correct way, but I got it working by inverting things so that underscore depends on underscore.string. Also, this way you don't have to require underscore.string.
.
Update: 3/14/2014
Underscore.js v1.6.0 brought back AMD compatibility and
init()
has been removed from RequireJS, so some refactoring is in order. To continue getting Underscore preloaded with Underscore.string I made a mixer module to pull them together.New Require.js config
underscore.mixed
The final step is to replace all instances of
'underscore'
with'underscore.mixed'
in module definitions. I attempted moving Underscore into a file namedunderscore.base.js
and making the regularunderscore
the mixer (like the Backbone setup) to avoid this step. Underscore, being a named module, disagreed with the plan.