GithubHelp home page GithubHelp logo

modules's Introduction

Modular system NPM version Build Status

по-русски

What? Why and what for? How to use? (ru)

Requirements

  1. Asynchronous require for modules
  2. Asynchronous provide for modules
  3. Extending and redefining a module

Why not CommonJS?

See #1, #2 and #3 in the list of requirements.

Why not AMD?

See #2 and #3 in the list of requirements.

API spec

Module declaration

void modules.define(
    String moduleName,
    [String[] dependencies],
    Function(
        Function([Object objectToProvide], [Error error]) provide,
        [Object resolvedDependency, ...],
        [Object previousDeclaration]
    ) declarationFunction
)

Module usage

void modules.require(
    String[] dependencies,
    Function([Object resolvedDependency, ...]) successCallbackFunction,
    [Function(Error error) errorCallbackFunction]
)

Modules storage configuration

void setOptions(Object options)
Available options
  • trackCircularDependencies - if set to false doesn’t track circular dependencies. true by default
  • allowMultipleDeclarations - if set to false denies module overloading and provides an error. true by default

Get current state of module in storage

String getState(String name)
Possible states
  • NOT_DEFINED - module wasn’t defined
  • NOT_RESOLVED - module was defined, but it hasn’t started resolving
  • IN_RESOLVING - resolving is in progress
  • RESOLVED - module is already resolved

Check for module existence in storage

Boolean isDefined(String moduleName)

Create yet another modules storage

Modules modules.create()

Example

modules.define(
    'A',
    ['B', 'C'],
    function(provide, b, c, prev) {
        var a = {};
        provide(a);
    });

modules.define(
    'B',
    function(provide) {
        var b = {};
        provide(b);
    });

modules.define(
    'C',
    ['B'],
    function(provide, b) {
        var c = {};
        provide(c);
    });

modules.define(
    'C',
    function(provide, prevC) {
        var nextC = {};
        provide(nextC);
    });

modules.require(
  ['A'],
  function(a) {
    // module 'A' now resolved to a
  });

modules's People

Contributors

dab avatar dfilatov avatar ikokostya avatar ilyar avatar jk708 avatar makishvili avatar mdevils avatar miripiruni avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modules's Issues

Add possibility to create multiple storages

At the moment ym provides interface to manipulate with the only private variable modulesStorage.
I need several instances with the similar or the same functionality to manipulate different kinds of modules separately.

Динамическая загрузка модуля.

Использую ym в составе bem/enb/i-bem для клиентского кода блоков. При попытке загружать файлы модулей динамически (через js document.createElement('script')... вместо статического <script src="..."></script>) происходит сбой и до вызова decl.fn.apply дело не доходит.

Насколько сейчас понимаю, дело в том, что modules.define определяется после отработки jQuery.ready (где происходит всё это шаманство с nextTick, requireDeps, startDeclResolving и пр.

Сейчас удалось добиться запуска модуля вызовом modules.require(...) после загрузки файла с кодом.

Насколько это нормально? Как лучше решать вопрос?

Описание проблемы на форуме bem.info

errorCallback в require

Сейчас невозможно узнать какой вызов require вызвал ошибку.
Было бы хорошо иметь возможность в require передавать errorCallback.

Сравнение с AMD (require.js, webpack)

Просьба описать use case, когда необходимы асинхронный provide и возможность передекларации модулей. Пока непонятно, зачем эти возможности нужны и чем это решение лучше require.js или webpack.

Обработка ошибки в define

Сейчас внутри define есть возможность выполнить асинхронную операцию и уведомить модульную систему отложено при помощи функции provide. Но нет никакой возможности уведомить о произошедшей ошибке. Если внутренняя асинхронная операция завершилась провалом, то модульная система об этом никогда не узнает.

Можно в provide вторым аргументом передавать ошибку. provide(null, Error).
Ошибка будет передана внешним слушателям, которые вызвали require. А все участвующие в цепочке модули вернутся к начальному состоянию (not resolved).

Возможность указать baseUrl

Require JS имеет опцию baseUrl, с помощью которой я могу указать, в каком месте находятся мои подмодули.
Как указать это в ym, чтобы все подмодули грузились из правильной папки?

What about adoption to AMD?

I don't see much changes in modules.require vs System.import, except in AMD dependencies can be file names.

But there are some differences in define:

modules.define(
  {String} moduleName,
  [{Array.<String>} dependencies,]
  {function (
    {function ( resolution, [{Error} error] )} provide,
    {Array.<*>} ...imports,
    [{*} prev]
  )} declarationFunction
);

What if we will compare dependencies.length with declarationFunction arity and decide with mind on that how to call declarationFunction?

It will help us to use modules as AMD module loader.

Is there any other problems or differences between current ym functionality and AMD standard?

Why I ask? Because ES6 modules comes to us. And I think about using ymodules for ES6 modules.

Ребят где скачать то саму библиотеку?

Вроде я программист, вроде неплохо разбираюсь, но чувствую себя полнейшим идиотом - не могу уже пол часа найти КАК НАЧАТЬ то?!?!

Вы написали как пользоваться, но где взять саму библиотеку?
Как я напишу
script src="YModules.js" type ="text/javascript"
??? где файл то взять??!?! почему нет в readme такой информации, я просто полностью не доумеваю вообще

One need fallback in cases of exceptions

The problem is simple - there is no way to detect or catch any exception in modules. For example i can require undefined module and i will not get any error.

Для чего используется nextTick

Какой смысл в выполнении require через nextTIck?

Возникла проблема: необходимо динамически подгрузить скрипт. Внутри скрипта modules.require использует уже определенные модули. Ожидаемый результат, что по script.onload коллбэк из modules.require уже будет выполнен. Возможно уже есть решение с динамической подгрузкой?

работа со сторонними библиотеками

Привет. Есть ли в модульной системе возможность работать с библиотеками которые не имеют синтаксиса ymaps/modules? Например библиотеки backbone, momentjs. Есть ли аналог shims из AMD, который бы позволял использовать эти библиотеки?

Add ability to identify, which of the module generation's dependency is not resolved

In case

modules.define('a', function(provide) { provide() });
modules.define('a', ['b'], function(provide, b, a) { provide(a) });
modules.define('a', ['c'], function(provide, c) { provide(a) });

so if b is not resolved, the error stack would be:

Uncaught Error: Module "a": can't resolve dependence "b" <file>
  throwModuleNotFound <file>
  calcDeclDeps <file>
  onNextTick <file>
  callFns <file>
  onMessage

It would be cool to have an ability to understand, from what of a's generation error comes

Can't resolve module if it comes in separate <script> tag

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>modules test</title>
</head>
<body>
<script>
    /* here comes modules v0.1.0 source */
</script>
<script>
modules.require(['A'], function(A) {
    A();
});
</script>
<script>
modules.define('A', function(provide) {
    provide(function() { console.log('test')});
});
</script>
</body>
</html>

It reproduces sometimes.
Open this HTML in Chrome, Yandex, Opera with opened console and press cmd+r until we get JS-error: Uncaught Error: Required module "A" can't be resolved. If we remove </script><script> between require and define then we can not reproduce this bug.

If don't call provide in decl process wait for infinity

Main problem is that you don't know that. And all what you can do is check all your code. Maybe you can add some stats method to call when something go wrong.
There is a method:

String getState(String name)

But if you has to many modules you just don't want to check them all.
I see solution in some dependency graph with states.
Minor example:

modules.define(
    'A',
    function(provide, prev) {
        var a = {};
        // do not call provide
        //provide(a);
    });

modules.require(
  ['A'],
  function(a) {
    /* never goes here */
  });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.