What is commonjs2 ?

Sorry if that’s obvious but it’s been eating me for multiple days and even greping commonjs2 through this repository I couldn’t find any obvious information.
My google-fu on commonjs2 led me back to #864 … which was not helpful.

Anyone could explicitely inform me what is commonjs2, the differences with commonjs, and what is the relation with webpack ?

Thanks …

Author: Fantashit

7 thoughts on “What is commonjs2 ?

  1. CommonJs spec defines only exports. But module.exports is used by node.js and many other CommonJs implementations.

    commonjs mean pure CommonJs
    commonjs2 also includes the module.exports stuff.

  2. So … the replacement of module.exports

    module.exports = function(){};

    instead of simply adding stuff to the exports object

    exports.a = 'a';
    exports.b = 'b;'

    is not in the “initial” commonjs spec ? nodejs started it and everybody followed ?

  3. Are there other commonjs implementations that do not use module.exports which need to be supported by webpack? Now that I understand what the two options commonjs and commonjs2 are, I would like to understand if there is a practical use case for commonjs.

  4. As described in the document, commonjs belongs to Expose Via Object Assignment, commonjs2 belongs to Module Definition Systems.

    Although the output of this two build(exports['MyLibrary'] = _entry_return_; and module.exports = _entry_return_;) is so similar, it seems Webpack treat them differently in importing. For example,

    I have a simple module:

    // const.js
    export let name = 'leon'
    export default function print() { console.log('print: ' + name) }

    I build this module as commonjs and commonjs2.

    Then, in another project, I try to import both modules, then I found Webpack can only handle commonjs2 correctly.

    import Const1, { name as name1 } from '../output/dist/index.cmd.js'
    import Const4, { name as name4 } from '../output/dist/index.cmd2.js'
    console.log(Const1, name1)
      Const1 is {
        MyLibrary: {
            default: print(){...},
            name: 'leon'
      name1 is undefined
    console.log(Const4, name4)  // Const4 is print function, name4 is 'leon'

    So it seems we should build the module as commonjs2 instead of commonjs, if we want to exports the moudle. This is why commonjs2 belongs to Module Definition Systems? 😂

Comments are closed.