define.js

0.1.0 • Public • Published

#define.js An asynchronous module system for all javascript environments (node.js, browsers, ...) that is meant to replace all standard module loaders (e.g. "require" of node.js) and to solve all problems in creating cross-environment code.

##why define.js? Since the "require" module system of node.js is synchronous, it is impossible to bring modules for it to the browser in a clean way. You'd eiter have to make blocking XHR's or to use tools like "node-browserify" to do it. This is NOT professional!

So, if you want to make cross-environment javascript modules, you'd have to use an asynchronous third-party module system. There are a lot of them (AMD, require.js, DefineJS, ...), so why define.js?

  • define.js has, except the asynchronous system, an identical API (module, exports, __filename, __dirname, ...)
  • porting over node.js modules to define.js is very simple & fast
  • you can load built in & normal node.js modules through define.js
  • you can hide server-only code to the browser very easy
  • you can build a whole application in one single file with all its dependencies for browserside usage

##defining a module

define(function(){
    exports.text = "Hello World!";
});

##defining a module that uses other modules

define("a","b",function(a,b){
    exports.a = a;
    exports.b = b;
});

##creating an app that uses a define.js module

require("define");
define(__filename,"mymodule",function(mymodule){
    mymodule.doSomething();
});

##loading node.js modules

define("http",function(http){
    http.createServer(function(req,res){
        res.end("Hello World!");
    }).listen(80);
});

##creating a package.json

{
    "name","mymodule",
    "define":"./mymodule.js"
}

##creating different entry points for browser and node.js

{
    "name":"mymodule",
    "define":{
        "node":"./server.js",
        "browser":"./client.js"
    }
}

##building a module with all its dependencies for browserside usage

require("define");

var code = define.build(__filename,"mymodule");

###saving it to a file

require("fs").writeFile("/where/i/want/to/store/the/module.js",code);

###sending it to the client

require("http").createServer(function(req,res){
    if(req.url = "/mymodule.js"){
        res.writeHead(200,{"content-type":"text/javascript"});
        res.end(code);
    }else{
        res.writeHead(200,{"content-type":"text/html"});
        res.end("<html>...</html>);
    }
}).listen(80);

###using it on the browser side

<html>
    <head>
        <script src="./mymodule.js"></script>
        <script>
            define("mymodule",function(mymodule){
                mymodule.doSomething();
            });
        </script>
    </head>
</html>

Readme

Keywords

none

Package Sidebar

Install

npm i define.js

Weekly Downloads

9

Version

0.1.0

License

none

Last publish

Collaborators

  • VanCoding