How to use underscore.string globally in a web page (with requireJS)

177 Views Asked by At

The documentation says once underscore.string included in my application, the library is available using s, __s global variables (http://epeli.github.io/underscore.string/#others), or within underscore properties __.str or __.string.

This simple code should then work properly (with config paths correctly set) :

require(['underscore','underscore.string'], function(){
     console.log(s('test').capitalize().value());
});

But it does not work at all. Here is a simple jsfiddle example. I probably did something wrong, but I can't figure out what.

https://jsfiddle.net/mvenrtgy/10/

The relevant test code is:

require.config({
  paths: {
    'underscore':'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min',
    'underscore.string':'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min'
  }
});
require(['underscore','underscore.string'], function(){

  var t = 'This is a simple text I would like to SLUGIFY using unsercore.string';

  // underscore is there!
  console.log(typeof _)

  // now check where underscore.string is...
  console.log(typeof _.str);
  console.log(typeof _.string);
  console.log(typeof s);
  console.log(typeof _s);

  document.getElementsByTagName('body')[0].innerHTML = '<p>Sample text : ' + t + '</p>';
  // this line will cause an error
  document.getElementsByTagName('body')[0].innerHTML += '<p><em>Slugified</em> text : ' + s(t).slugify().value() + '</p>';


});
1

There are 1 best solutions below

1
Louis On

underscore.string is a well-behaved AMD library so it does not pollute the global space. You should change your require call so that it gets the parameters that correspond to the modules you are loading:

require(['underscore','underscore.string'], function(_, s){

By just making this change to your code, I get something that works. The 2nd line of your test comes up as:

Slugified text : this-is-a-simple-text-i-would-like-to-slugify-using-unsercore-string

Also, while underscore.string started as an underscore extension, it has grown beyond that, so you cannot access it through the _ global that underscore leaks into the global space, unless you take care of mixing it in with underscore. The documentation says you can do this:

_.mixin(s.exports());

But the documentation recommends against it because underscore.string will interfere with some of the basic functions that underscore exports. Use at your own risks.