• Stars
    star
    305
  • Rank 131,747 (Top 3 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Chainable Module Definition (CMD) dependency loader for JavaScript

MelchiorJS

build status dependencies bountysource

Tiny JavaScript in-browser module loader that implements Chainable Module Definition API.

Melchior is the first library that fully implements the Draft proposed by John Wu and brings to life "the most javascripty" way to configure modules and its dependencies for in-browser use.

Melchior does not have dependencies on any JavaScript framework. It is small with around 3KB when minified.

An alternative to AMD and RequireJS

The idea behind chainable modules solves several nasty AMD patterns like long lines of declaring dependencies and provides simplicity and readability with its' visual-friendly and clean syntax.

As CommonJS is more good for non-browser environments, chaining modules with requires fit perfectly for in-browser use cases.

Install

You can download all necessary Melchior files manually or install it with Bower:

bower install melchiorjs

Usage

Common Melchior module consists of the several parts and may look as follows:

// create module
melchiorjs.module('yourModule')

// define dependencies
.require('dependencyUno')
.require('dependencyDuo')

// define the module body
.body(function () {
	// `dependencyUno` and `dependencyDuo` are available
	dependencyUno.doSomething();
	dependencyDuo.doSomething();

	// return methods for other modules
	return {
		method: function () { ... },
		anotherMethod: function () { ... }
	};
});

In the real world the most likely you will want to use other third-party libs. Melchior also works as dependency script loader and provides similar config syntax as RequireJS does.

Firstly you will need to specify a data-main entry point for all of your modules:

<script src="/path/to/melchior.js" data-main="/path/to/entry.js"></script>

Inside entry.js call melchiorjs.config() with paths object inside that will include paths to the all libraries that you want to use as Melchior modules.

melchiorjs.config({
	paths: {
		// path key the same as global that lib exposes
		// saves from optional `shim` property on config
		'jQuery': 'path/to/jquery',
		'underscore': 'path/to/underscore',
		'myModule': 'path/to/myModule',
		'app': 'path/to/app'
	},

	// provide shim to non-melchior modules
	shim: {
		// declare the global returned by library
		underscore: {
			exports: '_'
		}
	}
});

For more detailed information on how config works check documentation.

From this point you will be able to require dependencies. Modules names and paths keys should be the same in order to loader work properly.

melchiorjs.module('app')

// provide any alias for module as second param
.require('jQuery', '$')
.require('underscore', 'fun')
.require('myModule')

.run(function () {
	$.get('/api/books').done(function (books) {
		var filtered = fun(books).sortBy('title');
		myModule.doSomethingWithBooks(filtered);
	});
});

This repo contains a special examples folder where several types of applications using Melchior are presented.

Getting started guide

Documentation

config(options)

Initialize dependency script loader that will asynchronously load the modules from provided paths. All modules are loaded via XHR and then injected as script elements already prepared to use with melchiorjs.

Options

  • paths - hash-map like object of scripts that will be loaded. Keys are module names and values are paths to the files.

  • shim - object where third-party libs and traditional "browser globals" scripts are configured to declare the dependencies and set the value returned by module. There are 2 options for every shim object: deps which is array of dependency names and exports - string representative of global variable exposed by script.

  • timeout - ms amount of time to wait before XHR'ed script timeouts, default 5000

Melchior handles not melchiorjs modules like third-party libs and frameworks by wrapping them into melchiorjs.module(pathKey) automatically. If such framework has dependencies and they are properly added to shim option Melchior will resolve shim's deps as requires to the lib.

melchiorjs.config({
	paths: {
		// path key will be turned to the module name 
		// e.g. melchiorjs.module('angular')
		'angular': '//ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular',
		'ngRoute': '//ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular-route',
		'ngResource': '//ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular-resource',
		'underscore': '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore'
	},

	shim: {
		// `angular` will be inserted as required dependency
		// e.g. melchiorjs.module('ngRoute').require('angular').body(...)
		ngRoute: {
			deps: ['angular']
		},
		ngResource: {
			deps: ['angular']
		},

		// lib exports `_` variable as global
		// e.g. melchiorjs.module('underscore').body(function() { return _; })
		underscore: {
			exports: '_'
		}
	}
});

The good example could be an Angular.js app.

module(name)

Create a module. You should specify a unique module name.

melchiorjs.module('yourModule');

It is possible for module name to have the namespace. A valid namespace should consist of several words and be separated by dots (.). Melchior takes the value after last dot as module name.

// `utils` will be considered as module name
melchiorjs.module('core.utils');

require(moduleName, [alias])

Define module dependencies. Once a dependency is declared, it will be assigned to a variable in the scope of the module body with the same name as the module name. You can use method chaining to declare multiple dependencies.

melchiorjs.module('core.utils')
.require('core.bar')
.require('core.foo')
.body(function () {
	// `foo` and `bar` are available in the scope of the module

	return {...}
});

Dependencies can have aliases. Just put an alias String value as the second parameter.

melchiorjs.module('core.utils')
.require('core.foo', 'bar') // created `bar` alias
.body(function () {
	// `bar` is available here

	return {...}
});

body(fn)

Declares module functionality. The only argument is module function which will be executed when all dependencies will be ready.

melchiorjs.module('core.doubles')
.body(function () {
	var multiplier = 2;

	return function (num) {
		return num * multiplier;
	};
});

run(fn)

Programmatically it's the same as body but use-cases might be a bit different. Recommended to use as the entry point for other modules.

melchiorjs.module('core')
.require('core.doubles')
.run(function () {
	var twenty = doubles(10);

	// will output `20`
	console.log(twenty);
});

Browser support

Melchior was tested successfully and officially supports:

Chrome Firefox IE Opera Safari
1+ βœ” 2+ βœ” 8+ βœ” 10+ βœ” 3+ βœ”

Contribution

Despite that Melchior is small and has very minimalistic API it may be not perfect yet. So if you found a bug or have an idea how to make it better do not hesitate to create an issue or even send a pull request.

References

Thanks John Wu for amazing idea and inspiration.

Library name is inspired by Evangelion's MAGI supercomputer. ✌️

Ireul Hacking Magi

Library also has landing page - http://labs.voronianski.dev/melchior.js

License

MIT Licensed

Copyright (c) 2014-2015 Dmitri Voronianski [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

flux-comparison

πŸ“ Practical comparison of different Flux solutions
JavaScript
2,785
star
2

oceanic-next-color-scheme

πŸ“ Sublime Text color scheme ready for next generation JavaScript syntax
JavaScript
1,972
star
3

jquery.avgrund.js

Avgrund is jQuery plugin with new modal concept for popups
JavaScript
1,764
star
4

react-swipe

↔️ Swipe.js as a React component
JavaScript
1,662
star
5

ngActivityIndicator

Angular provider for preloader animations
CSS
644
star
6

esnextbin

🍱 Prototype apps in the browser with next generation JavaScript and NPM modules
JavaScript
463
star
7

ngprogress-lite

Angular provider for slim progress bars
HTML
394
star
8

react-native-effects-view

Use iOS8 UIVisualEffectViews's blur and vibrancy with ReactNative
Objective-C
387
star
9

react-star-rating-component

Basic React component for star (or any other icon based) rating elements
JavaScript
378
star
10

realtime-geolocation-demo

Realtime geolocation with HTML5 API and Socket.io
JavaScript
337
star
11

soundcloud-audio.js

🎡 SoundCloud tracks and playlists with HTML5 Audio API
JavaScript
285
star
12

swipe-js-iso

Universal (a.k.a isomorphic) version of Swipe.js
JavaScript
189
star
13

universal-react-flux-boilerplate

React (0.13.x) + Flux (Flummox) + ReactRouter (0.13.x) + Server Rendering
JavaScript
170
star
14

simon-le-bottle

Getting started with Facebook Messaging Platform
JavaScript
111
star
15

dookie-css

stylus driven css library
CSS
109
star
16

node-tweet-cli

Start making tweets from your bash, zsh, whatever!
JavaScript
83
star
17

xml2obj-stream

XML to JavaScript object low memory streaming parser based on node-expat
JavaScript
63
star
18

griddy.css

πŸ“– Responsive 12 column based grid in 311 Bytes gzipped
HTML
63
star
19

ngKookies

Powerful replacer for built-in Angular's $cookieStore (https://github.com/angular/angular.js/issues/950)
JavaScript
60
star
20

is-express-schema-valid

🏁 express.js middleware that validates body, params, query of request according to JSONSchema and is extremely fast
JavaScript
59
star
21

node-object-encrypter

Encrypt/decrypt javascript objects as base64 strings with optional TTL support
JavaScript
58
star
22

express-api-sample

Sample API ready to be used in different client app boilerplates and playgrounds.
JavaScript
48
star
23

babel-transform-in-browser

Transform ES2015 in browser on the fly with Babel.js
JavaScript
45
star
24

node-tiny-dploy

Simple shell script + PM2 deployer
JavaScript
42
star
25

dumbugger

Automatically google for similar JavaScript errors when thrown.
HTML
38
star
26

node-grvtr

grvtr.js - small node.js gravatar library
JavaScript
32
star
27

node-config-boilerplate

Easy configs for node.js apps
JavaScript
28
star
28

react-pikaday-component

Universal React component wrapper around Pikaday.js datepicker
JavaScript
19
star
29

psi-local-cli

Google PageSpeed Insights CLI for localhost (via ngrok)
JavaScript
18
star
30

data-structures-and-algorithms-in-javascript

Basic data structures and algorithms implemented in JavaScript
JavaScript
16
star
31

Do-I-Know-JS

Javascript patterns uncovered with examples
JavaScript
13
star
32

setup-osx-work-station

🎁 OS X machine setup shell script
Shell
11
star
33

is-my-schema-valid

Simple function that validates data according to JSONSchema
JavaScript
9
star
34

versionify-assets

Function to get checksum of file and add to url querystring for cache busting
JavaScript
7
star
35

vapor-favicon-middleware

Favicon serving middleware for Vapor applications.
Swift
6
star
36

react-router-hooks-patch

Patch react-router route handler components with static hook methods onEnter/onLeave
JavaScript
6
star
37

uneasy-flux-demo

Practical flux to manage uneasy API scenarios like handling errors or pending requests
JavaScript
5
star
38

create-static

Create static html pages with esnext, scss and nunjucks easily.
JavaScript
5
star
39

c0nfig

Require local configs as if they are in node_modules
JavaScript
5
star
40

EightTracksSwift

8tracks radio client for iOS8 implemented in Swift
Swift
5
star
41

EightTracksReactNative

8tracks radio client for iOS powered by ReactNative
JavaScript
4
star
42

update-to-latest

Simple cli tool for easy update of npm dependencies.
JavaScript
3
star
43

waveform.js

Waveform.js makes drawing SoundCloud waveforms simple
JavaScript
3
star
44

node-shufflerfm

Shuffler.fm API client for Node.js
JavaScript
3
star
45

discogs-wantlist-cli

πŸ“€ Extract releases from Discogs user wantlist without duplicates.
JavaScript
2
star
46

vapor-server-example

Examples of server-side Swift powered by Vapor.
Swift
2
star
47

go2url.xyz

🌍 Change window.location in a second
HTML
2
star
48

swapi-graphql-react-app

SPA that allows to πŸ”Ž search for all human characters in 🌠 Star Wars saga.
JavaScript
2
star
49

react-waves

Top sounds of the web built with React components
JavaScript
2
star
50

isomorphic-flux-comparison

2
star
51

react-ace-preact-compat-issue

JavaScript
2
star
52

vapor-checksum-assets

Add checksums of .js/.css files to url querystring in Vapor applications for cache busting.
Swift
2
star
53

telepath-mini

Tiny and smart music player for OS X
CSS
2
star
54

melchior-landing

CSS
2
star
55

multi-translator

Get transations from several dictionaries in one app.
JavaScript
2
star
56

luvit-static-server-demo

Static server demo based on luvit.io
Lua
2
star
57

next-13-ninetailed-middleware-issue

TypeScript
1
star
58

soundcloud-api-proxy

🎢 Just a simple proxy server for not letting to abuse my SoundCloud client secrets.
JavaScript
1
star
59

vue2-examples

Playing with Vue 2.0 beta
JavaScript
1
star
60

izzit-mac-client

1
star
61

nooop

Just a noop function
JavaScript
1
star
62

fluid-layout-with-boxes

Small cross-browser hack in pure JS
JavaScript
1
star
63

universal-react-router-flux-2016

Opionated example of universal app setup
JavaScript
1
star
64

latest-browsers-api

JSON API to get the latest browser versions.
JavaScript
1
star
65

monqo-query-cli

make mongo shell queries from bash
JavaScript
1
star
66

contrabass.css

CSS utility belt in 1.99 kB
CSS
1
star
67

demo-tracker-app

demo of time tracker app written in angular
JavaScript
1
star
68

hamlet-boilerplate

App template for getting started with Hamlet
JavaScript
1
star
69

hash-unhash-exercise

JavaScript
1
star
70

angular_tuts

JavaScript
1
star
71

vapor-url-shortener

Basic url shortener API implemented in Swift and Vapor
1
star
72

webpack-trouble-demo

Webpack-dev-server + Existing node.js server = Some troubles
JavaScript
1
star