Difference between RequireJS and CommonJS

后端 未结 2 972
小鲜肉
小鲜肉 2020-11-29 05:30

I was wondering what the difference between these snippets is.

var $ = require(\'jquery\');
var _ = require(\'underscore\');
var BackBone = require(\'backbon         


        
2条回答
  •  清歌不尽
    2020-11-29 05:49

    The former snippet adheres to the CommonJS spec, which outlines how modules are to be exported/transported to be used in other modules.

    So, you could write code which could look like this

    src/ExpressModule.js

    var express = require('express');
    // do initialization
    exports.express = express;
    

    And then you can use it like this

    src/UserExpressModule.js

    var express = require('./ExpressModule');
    // do something else
    

    CommonJS spec was built primarily for server side environments, and by extension, is used in Node.js

    On the other hand of the spectrum is AMD, most notably implemented by RequireJS. AMD was built for browser environments, or client-side code, and here you can use and define modules like the latter snippet in your code

    A sample use could be like this

    src/main.js

    requirejs.config({
        baseUrl: '../vendor'
        path: '../src'
    });
    require(['jquery', 'underscore', 'backbone'], function($, _, Backbone) {
        // do some client side computation here
    });
    

    You can then include this main.js file in your index.html like so

    
    

    Essentially, CommonJS and AMD are at their core specifications for modularizing Javascript, but are aimed at different execution environments.

提交回复
热议问题