• Stars
    star
    126
  • Rank 274,375 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 3 years ago

Reviews

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

Repository Details

Gulp plugin for build JavaScript files as Universal Module Definition, aka UMD

gulp-umd

Build Status

This repository provides a simple way to build your files with support for the design and implementation of the Universal Module Definition (UMD) API for JavaScript modules. These are modules which are capable of working everywhere, be it in the client, on the server or elsewhere.

The UMD pattern typically attempts to offer compatibility with the most popular script loaders of the day (e.g RequireJS amongst others). In many cases it uses AMD as a base, with special-casing added to handle CommonJS compatibility.

Variations

Regular Module

See more variation options that can be added as templates onto this project on the UMD (Universal Module Definition) patterns.

Options

The following options are the ones available with the current default values:

{
  dependencies: function(file) {
    return [];
  },
  exports: function(file) {
    return capitalizeFilename(file);
  },
  namespace: function(file) {
    return capitalizeFilename(file);
  },
  templateName: 'amdNodeWeb',
  template: path.join(__dirname, 'templates/returnExports.js'),
  templateSource: 'module.exports = <%= exports %>'
}
  • dependencies: Function which returns an array of dependencies. Each dependency is specified either as a string, or as an object of the form.

    {
      dependencies: function (file) {
        return {
          name: 'defaultModuleName',
          amd: 'moduleNameInAMD',
          cjs: 'moduleNameInCommonJsAndNodeJs',
          global: 'moduleNameInBrowserGlobals',
          param: 'ModuleIdentifier'
        }
    }
  • exports: Specifies the item (or for CommonJS, item's) which the module will export. For non CommonJS, this value should be a string specifying the exported item.

    {
      exports: function (file) {
        return 'Foo.Bar';
      }
    }

    For CommonJS, this value should be an object with keys specifying the names and values specifying the exported items.

    {
      exports: function (file) {
        return {
          'Foo': 'Foo',
          'FooBar': 'Foo.Bar'
        };
      }
    }
  • namespace: Specifies the global namespace to export to. Only used for Web globals.

    {
      namespace: function (file) {
        return 'My.Global.Namespace';
      }
    }
  • templateName: Specifies the name of the template to use. Available template names are amd, amdNodeWeb, amdCommonWeb, amdWeb, common, node, returnExports and web. See above for descriptions. If specified, overrides the template and templateSource.

    {
      templateName: 'amdNodeWeb'
    }
  • templateSource: Specifies the lodash template source to use when wrapping input files. If specified, overrides template.

    {
      template: '<%= contents %>'
    }
  • template: Specifies the path to a file containing a lodash template to use when wrapping input files.

    {
      template: '/path/to/my/template'
    }
    

Examples

Build a simple module

Let's wrap src/foo.js file with UMD definition:

'use strict';
function Foo() {}

Then, in the gulp task:

gulp.task('umd', function() {
  return gulp.src('src/*.js')
    .pipe(umd())
    .pipe(gulp.dest('build'));
});

After build build/foo.js will look like:

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.Foo = factory();
  }
}(this, function() {
'use strict';
  function Foo() {}
  return Foo;
}));

Note that by default the filename foo.js is uppercased and will be used as the return exports for your module and also for the global namespace, in this case root.Foo. This is configurable, see the advanced build section below.

Build with dependencies

Let's wrap src/foo.js file with UMD definition defining some dependencies:

'use strict';
function Foo() {}

Then, in the gulp task:

gulp.task('umd', function(file) {
  return gulp.src('src/*.js')
    .pipe(umd({
        dependencies: function(file) {
          return [
            {
              name: 'moduleName1',
              amd: 'moduleName1_amd',
              cjs: 'moduleName1_cjs',
              global: 'moduleName1_glob',
              param: 'moduleName1'
            },
            {
              name: 'moduleName2',
              amd: 'moduleName2_amd',
              cjs: 'moduleName2_cjs',
              global: 'moduleName2_glob',
              param: 'moduleName2'
            }
          ];
        }
      }))
    .pipe(gulp.dest('build'));
});

After build build/foo.js will look like:

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['moduleName1_amd', 'moduleName2_amd'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('moduleName1_cjs'), require('moduleName2_cjs'));
  } else {
    root.Foo = factory(root.moduleName1_glob, root.moduleName2_glob);
  }
}(this, function(moduleName1, moduleName2) {
'use strict';
  function Foo() {}
  return Foo;
}));

The advanced configuration for the dependencies allows you to have full control of how your UMD wrapper should handle dependency names.

Advanced build

Let's wrap src/foo.js file with UMD definition and exports the Foo.Bar class:

'use strict';
function Foo() {};
Foo.Bar = function() {};

Then, in the gulp task:

gulp.task('umd', function() {
  return gulp.src('src/*.js')
    .pipe(umd({
      exports: function(file) {
          return 'Foo.Bar';
        },
        namespace: function(file) {
          return 'Foo.Bar';
        }
    }))
    .pipe(gulp.dest('build'));
});

After build `build/foo.js will look like:

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.Foo.Bar = factory();
  }
}(this, function() {
'use strict';
  function Foo() {};
  Foo.Bar = function() {};
  return Foo.Bar;
}));

Templates

In order to use any of the variations defined on the UMD (Universal Module Definition) patterns repository you can use the following template keys:

  • <%= amd %>: Contains the AMD normalized values from the options dependencies array, e.g. ['a', 'b'] turns into ['a', 'b'].
  • <%= cjs %>: Contains the CommonJS normalized values from the options dependencies array, e.g. ['a', 'b'] turns into require('a'), require('b').
  • <%= commaCjs %>: As above, prefixed with ', ' if not empty.
  • <%= global %>: Contains the browser globals normalized values from the options dependencies array, e.g. ['a', 'b'] turns into root.a, root.b.
  • <%= commaGlobal %>: As above, prefixed with ', ' if not empty.
  • <%= namespace %>: The namespace where the exported value is going to be set on the browser, e.g. root.Foo.Bar.
  • <%= exports %>: What the module should return, e.g. Foo.Bar. By default it returns the filename with uppercase without extension, e.g. foo.js returns Foo. If using CommonJS, this value may be an object as specified by the result of options.exports
  • <%= param %>: Comma seperated list of variable names which are bound to their respective modules, eg a, b.
  • <%= commaParam %>: As above, prefixed with ', ' if not empty.

You can also use umd-templates, using the patternName.path property if template option is used, and patternName.template if templateSource is used.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -m 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

More Repositories

1

tracking.js

A modern approach for Computer Vision on the web
JavaScript
9,406
star
2

dotfiles

[DEPRECATED] The first JavaScript-based dotfiles powered by Grunt.
Shell
422
star
3

jquery-simulate

jQuery Simulate is a plugin to simulate browser mouse and keyboard real events
JavaScript
102
star
4

video-camera-element

Web Component wrapper for getUserMedia API using Polymer
JavaScript
86
star
5

tracking-elements

Web Component wrapper for tracking.js API using Polymer
JavaScript
71
star
6

trackingjs.com

Website of tracking.js library
CSS
25
star
7

yui-combo

Designed to be used to generate the combo file for the request made from loader.js using YUI3. In summary, read the parameters keys (combo files), concatenate them, gzip, cache, set the HTTP headers, print out the combo file.
PHP
9
star
8

rsa-prime-factorization

Prime factorization is known as a way to crack the RSA cryptosystem code. Currently, most of the best modern factoring algorithms are based on the idea behind Fermat's method of factorization. This project explain how to use Fermat's method to find the prime factorization of a number.
Java
9
star
9

car-plate-segmentation

Extract possible rectangle segments on images representing car plates regions and detect connected segments on binary images to extract the letters and numbers.
MATLAB
8
star
10

snippets

This is a personal Sublime Text Snippets backup — Use at your own risk.
7
star
11

msc-ufpe-thesis

Thesis presented to the Post-Graduation Program in Computer Science Program of Federal University of Pernambuco in partial fulfillment of the requirements for the Master Degree of Computer Science.
Python
5
star
12

yfast

YFast is a PHP class developed to use on this blog, it gives you the possibility to use all modern technics of web development (etags, gzip, exipire headers) on your site in a very simple way -- and get A on YSlow.
PHP
5
star
13

node-zip-archiver

This project provides a simple Zip compression API for NodeJS using archiver.
JavaScript
4
star
14

color-blindness-simulator

Color Blindness Simulator, Monochromacy (complete), Protanopia (complete red-green), Deuteranopia (complete red-green)
MATLAB
3
star
15

sublime-tubsted-color-scheme

Slightly modified version of Tubster Color Theme for my taste.
3
star
16

image-documents-limiarization

Limiarize images of documents and extract region properties for possible text lines
MATLAB
3
star
17

cli-log

This project provides common log methods for your nodejs command line app.
JavaScript
1
star
18

jazz

A Java SASS and Compass Wrapper: It is the missing tool that you need to integrate SASS and Compass in your JAVA projects.
Java
1
star
19

madvoc-route

JavaScript parser for Madvoc routes configuration file
JavaScript
1
star
20

alloyui.com

Website for AlloyUI
JavaScript
1
star