Pergunta

Is there a quick way to import libraries from the js/coffee console? Right now, every time I need to use a library, I inject a script element linking the cdn to my DOM like this:

var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

This is really a pain. There must be some way to store commonly used libraries locally, then allow my console to use requirejs or something to import them in one line (and without remembering the cdn url). I'm a python guy, I'm very accustomed to being able to plug n' play with any installed module in my PATH. I'd like to be able to play with js in a similar way-- it's how I learn best.

Foi útil?

Solução

Sorry, but not completely in the way you want. But you could set up a lab environment for yourself where you make libraries a little quicker to load by giving it a short name and fetch the libraries via cdnjs, they have reasonably predictable URL path names.

The function would look a bit like this:

window.jsopen = function(path) {
  var el = document.createElement('script');
  if(path.indexOf('http') == 0) {
    el.src = path;
  } else {
    el.src = '//cdnjs.cloudflare.com/ajax/libs/'+path;
  }
  document.head.appendChild(el);
}

Embed that in a piece of simple HTML and open developer tools, and open the CDNJS site in a tab beside it. Now you should be able to import libraries either by their full URL, or by the final part of their path there. With jQuery in your example it would be reduced to:

> jsopen('jquery/2.0.3/jquery.min.js')
undefined
> $
function (e,n){return new x.fn.init(e,n,t)}

It's still nothing like what you could get on Python, but it's a little bit better than doing the whole thing as you describe in your question.

Also notice that the function doesn't (can't) know about dependencies, so:

> jsopen('backbone.js/1.1.2/backbone-min.js')
undefined
Uncaught TypeError: Cannot call method 'each' [...]

but:

> jsopen('underscore.js/1.6.0/underscore-min.js')
undefined
> jsopen('backbone.js/1.1.2/backbone-min.js')
undefined
> Backbone
Object {VERSION: "1.1.2", $: function,

Advanced version: you can make a lab environment that do know about dependencies with a combination of Browserify and NPM.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top