Jasch1 Jasch1 - 1 year ago 48
Javascript Question

Build a single JavaScript library file into multiple modules types (e.g. AMD, CommonJS, or whatever...)

In one way this sounds like a simple idea in my head but then I think of how to implement it and quickly run into problems.
I need to write a module with some functions, etc, etc. I've usually written it in AMD format and built with RequireJS optimizer. Long story short I now have a requirement to provide the library in other formats too and trying to figure out if there's a good way to have 1 single file for the core-code of the module and run tasks to output it in whatever module formats I need.

(I know I'll be asked why am I even doing this which is a long story but this is infact the requirement)

Answer Source

You essential want UMD (Universal Module Definition). You can check it out here: https://github.com/umdjs/umd

Basically, it's a small snippet of code that wraps your module in a factory function and takes that factory and determines how to export it based on the environment it's in. Here's a small snippet:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.MyModule = factory();
}(this, function myModuleFactory() {

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};