How does library import work in JavaScript?

10
In programming languages such as Java, C # and C, when we want to use some command or function we must include the library where it contains the commands we want or the classes if it is an object oriented language, see examples:

Class Scanner of Java that belongs to package util , we use the command import to use this class:

import java.util.Scanner;

Codigo...

Class Regex of C # that belongs to the RegularExpressions package, we use the using command to use this class:

using System.Text.RegularExpressions;

Codigo...

Function pow() of C that belongs to library math.h , in this case we use #include to use function:

#include <math.h>

Codigo...

But in JavaScript I realize that this is not the case, I just type the command I want for example console.log() or array.push('Stack') and use whatever method or class I want.

My question:

I would like to know how library import works in JavaScript and how does JavaScript manage your libraries as much as the language itself as third-party libraries?

    
asked by anonymous 08.05.2016 / 22:43

1 answer

9

Being concise it can be said that there are 3 different generations in importing libraries.

  • including the library in the global space (the oldest and most common)
  • using package managers / libraries / dependencies (for those who know and need them)
  • using import (the future, ES6 and ES7)

The most common way today is to import into global space by inserting the file directly on the page. Examples of this are jQuery , Angular , Mootools , etc. when loaded into HTML with for example:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Inthiswaythevariablesthatareglobalinthisfilewillbeglobalinmyapplication.

Thisissimple,butcancauseproblemswhenimportingcodethatexportsmanyvariables/namestoglobalspace.Ifwethinkthateachapplicationcanhave20.jsfilestoloadthenitiseasytoseethattheprobabilityofoverlappingnamesandvariablesthateraseothersisgreat.Thisworkswellonsmallprojectsandwheretheauthorhascontrol/knowledgeofwhichfilestoincludeintheapplication.

Managerssuchas require.js and browserify (which converts modules in Node.js to the browser).

The idea is simple, these programs load the required libraries and their dependencies, and then expose chosen variables from those libraries to a defined / limited scope. That is, the code that we have is never run in the global space, but rather within functions to limit the scope and only with access to the variables that the module manager has configured. Basically, minimalist example:

requirejs(['jquery'], function( $ ) {
    // aqui dentro o $ do jQuery está disponivel.
    // o código da aplicação coloca-se a partir daqui
});

Parallel to this more or less common reality in the browser came Node.js, which is JavaScript on the server side. Then the CJS model was adopted. That basically causes each never file to export to global space, and everything that enters the file (module) must enter via require .

var $ = require('jquery');
exports.myExample = function () {};

This would be the equivalent exepmlo, although jQuery is not used in Node.js. But according to the comparison we see that within this file $ is available after the module is requested and assigned to the variable. exports is the ticket to the outside world and is what will be passed to the next variable that does var x = require(etc...);

The future is to use [import 3 which is part of the ES6 and ES7 specifications but is not yet available in browsers. These modules (in times called Harmony) are modeled after the Node.js (CJS). Although this is in the future, it is however possible today to write JavaScript with this syntax and then convert to the browser with Babelify (Babel + Browserify), which are simulators (very reliable and widely used). So write code that does not have to be changed in the future.

This new way of loading dependencies is very useful and expected. In this future case the syntax is:

// para importar todas as variáveis globais nesse "meu-modulo"
// e colocar numa nova variável chamada "meuModulo":
import * as meuModulo from "meu-modulo"; 

// para importar somente a variável meuModulo desse "meu-modulo"
import {meuModulo} from "meu-modulo"; 

// para importar e dar novo nome ao mesmo tempo (multiplos nomes/variáveis neste exemplo)
import {meuModulo as m, calculadora as c} from "meu-modulo"; 

An important difference between this model and CJS is that in ES6 / 7 it is possible to use export multiple times to make these features available to "who to import".

An example:

file main.js

import {closest, getElements} from 'utils';
// ou até import * as utils from 'utils'
getElements('div').forEach(el => {
    el.innerHTML = 'foo';
});

file utils.js

export function getElements(what, rel) {
    if (typeof what != 'string' && typeof what != 'undefined') return what.tagName ? [what] : what;
    var els = (rel || document).querySelectorAll(what);
    return [].slice.call(els);
}
export function getClosest(el, selector) {
    while (el && !el.matches(selector)) {
        el = el.parentElement;
    }
    return el;
}
    
08.05.2016 / 23:26