javascript – Prompt modular js system

Question:

Started programming in js, but little experience. I would like to have an analogy with classes as in php. To write a module in one file and then, if necessary, connect it in a file. + It would be an advantage so that it can then be compiled into 1 js file. Please tell me which framework or library to use for these needs? Or perhaps some kind of article touching on this topic will not be superfluous. Thank you

Answer:

In the modern JavaScript ecosystem, there are several approaches to dividing code into modules:

  1. AMD is the module description format used in Require.js . In my (very subjective) opinion, the description of the modules is somewhat redundant. One of the main "chips" – asynchronous dynamic loading of modules on demand. Although, if memory serves, it is also possible to collect all the code into one package . Example of AMD module description:

     // Описание зависимостей define(['jquery', 'foo', 'bar'], function (jquery, foo, bar) { // Определение самого модуля return function () {}; });
  2. Common.js is an approach used, for example, in the Node.js ecosystem. A typical module looks like:

     // Импортируем зависимости var jquery = require('jquery'), foo = require('foo'), bar = require('bar'); // Экспортируем тело модуля module.exports = function() {};
  3. UMD is a combined approach that allows you to describe modules that run in both AMD infrastructure and Common.js. It is nothing more than a compatibility tool.

  4. ES2015 Modules is a special syntax introduced in the ES2015 standard that allows you to break code into modules. Example module:

     // Импортируем зависимости import 'jquery' as $; import foo from 'foo'; import bar from 'bar'; // Экспортируем тело модуля export default function() {};

The bad news is that none of the approaches to describing modules can work directly in the browser. In any case, you will have to include some third-party library for managing modules. For AMD, this is Require.js ; for Common.js – Browserify , Webpack and others; for ES2015 – it can be a bunch of Browserify + Babel or something else.

For new projects, I would recommend that you pay attention to ES2015 modules and Common.js modules. There are several reasons for this:

  • The Node.js ecosystem uses Common.js modules. Using a build system like Browserify you can use npm modules. This will allow you to write code that will run on both the server and the client.
  • With modern build systems, you should be able to combine ES2015 and Common.js modules with almost no problem.
  • Although today browsers do not have built-in ES2015 module loading tools, things are heading towards the fact that sooner or later they will appear.

What to read:

Scroll to Top