├── .gitignore ├── .jshintrc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── demo.js ├── index.js ├── package.json ├── templates ├── returnExportsGlobal.hbs ├── umd+rails.hbs ├── umd.hbs └── unit.hbs └── tests ├── amd-with-deps-and-alias.js ├── amd-with-deps.js ├── amd.js ├── amd_loader.js ├── browser-with-deps-and-alias.js ├── browser-with-deps.js ├── browser.js ├── cjs.js ├── data ├── amd.js ├── browser.js ├── demo.js ├── with-deps-and-alias.js └── with-deps.js ├── index.js └── utils.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "bitwise": true, 3 | "browser": true, 4 | "camelcase": false, 5 | "curly": true, 6 | "eqeqeq": true, 7 | "esnext": true, 8 | "immed": true, 9 | "indent": 4, 10 | "latedef": false, 11 | "newcap": true, 12 | "noarg": true, 13 | "node": true, 14 | "quotmark": "single", 15 | "strict": true, 16 | "trailing": true, 17 | "undef": true, 18 | "unused": true, 19 | "sub": true, 20 | "globals": { 21 | "node": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | - "5" 5 | - "6" 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 0.9.0 / 2017-12-04 2 | ================== 3 | 4 | * Breaking - Use global alias in AMD everywhere. #21 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Juho Vepsalainen 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![build status](https://secure.travis-ci.org/bebraw/libumd.png)](http://travis-ci.org/bebraw/libumd) 2 | 3 | # libumd - Wraps given JavaScript code with UMD 4 | 5 | ## Usage 6 | 7 | ```js 8 | var umdify = require('libumd'); 9 | 10 | ... 11 | 12 | var result = umdify(js, options); 13 | ``` 14 | 15 | > `libumd` doesn't guarantee pretty formatting. It is better to use something like [js-beautify](https://www.npmjs.com/package/js-beautify) to deal with that. 16 | 17 | ## Options 18 | 19 | ```js 20 | { 21 | template: 'path to template or template name', // defaults to 'umd' 22 | amdModuleId: 'test', // optional AMD module id. defaults to anonymous (not set) 23 | globalAlias: 'alias', // name of the global variable 24 | deps: { // dependencies 25 | // use default only if the module name and the variable the module will be injected with is the same 26 | 'default': ['Foo', 'Bar'], 27 | // additionally define these if the module name differs from the variable with which it will be used 28 | // note how we can map dependencies to specific parameters 29 | amd: ['foo', {'lodash': '_'}], 30 | cjs: ['foo', 'bar'] 31 | } 32 | } 33 | ``` 34 | 35 | > Check out the [`demo.js`](https://github.com/bebraw/libumd/blob/master/demo.js) 36 | 37 | ## Default Templates 38 | 39 | The library comes with a couple of UMD variants at `/templates`. In addition you may use one of your own as long as it is formatted using Handlebars syntax and follows the same naming conventions as the ones provided with the project. 40 | 41 | ## Testing 42 | 43 | Make sure [PhantomJS](http://phantomjs.org/) is installed and it's within your PATH. Hit `npm test` after that. If the UMD wrapper fails to run against the headless browser, you'll know. 44 | 45 | ## Contributors 46 | 47 | * [Stéphane Bachelier](https://github.com/stephanebachelier) - Use existing `objectToExport` instead of hardcoded value `returnExportsGlobal` for AMD. 48 | * [Simon Harte](https://github.com/SimonHarte) - Made the documentation clearer about the correct usage. 49 | * [Valerii Zinchenko](https://github.com/valerii-zinchenko) - Allowed dependency name to contain a dash. #17 50 | * [@timeiscoffee](https://github.com/timeiscoffee) - Updated UMD templates to the current scheme. #18 51 | 52 | ## License 53 | 54 | `libumd` is available under MIT. See LICENSE for more details. 55 | 56 | -------------------------------------------------------------------------------- /demo.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var umdify = require('./'); 3 | 4 | main(); 5 | 6 | function main() { 7 | var result = umdify('demo();', { 8 | deps: { 9 | // use default only if the module name and the variable the module will be injected with is the same 10 | 'default': ['Foo'], 11 | // additionally define these if the module name differs from the variable with which it will be used 12 | 'amd': ['foo'], 13 | 'cjs': ['foo'] 14 | } 15 | }); 16 | 17 | console.log(result); 18 | /** 19 | (function (root, factory) { 20 | if (typeof define === 'function' && define.amd) { 21 | // AMD. Register as an anonymous module unless amdModuleId is set 22 | define(["foo"], function (a0) { 23 | return (factory(a0)); 24 | }); 25 | } else if (typeof exports === 'object') { 26 | // Node. Does not work with strict CommonJS, but 27 | // only CommonJS-like environments that support module.exports, 28 | // like Node. 29 | module.exports = factory(require("foo")); 30 | } else { 31 | factory(Foo); 32 | } 33 | }(this, function (Foo) { 34 | 35 | demo(); 36 | 37 | })); 38 | */ 39 | } 40 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var EventEmitter = require('events').EventEmitter; 4 | var inherits = require('util').inherits; 5 | var fs = require('fs'); 6 | var path = require('path'); 7 | 8 | var alphabet = require('alphabet').lower; 9 | var handlebars = require('handlebars'); 10 | var objectMerge = require('object-merge'); 11 | var is = require('annois'); 12 | var zip = require('annozip'); 13 | 14 | 15 | var UMD = function UMD(code, options) { 16 | if(!code) { 17 | throw new Error('Missing code to convert!'); 18 | } 19 | 20 | EventEmitter.call(this); 21 | this.code = code; 22 | this.options = options || {}; 23 | 24 | this.template = this.loadTemplate(this.options.template); 25 | }; 26 | 27 | inherits(UMD, EventEmitter); 28 | 29 | UMD.prototype.loadTemplate = function loadTemplate(filepath) { 30 | var tplPath, 31 | exists = fs.existsSync; 32 | 33 | if (filepath) { 34 | if (exists(filepath)) { 35 | tplPath = filepath; 36 | } 37 | else { 38 | tplPath = path.join(__dirname, 'templates', filepath + '.hbs'); 39 | 40 | if (!exists(tplPath)) { 41 | tplPath = path.join(__dirname, 'templates', filepath); 42 | 43 | if (!exists(tplPath)) { 44 | this.emit('error', 'Cannot find template file "' + filepath + '".'); 45 | return; 46 | } 47 | } 48 | } 49 | } 50 | else { 51 | tplPath = path.join(__dirname, 'templates', 'umd.hbs'); 52 | } 53 | 54 | try { 55 | return handlebars.compile(fs.readFileSync(tplPath, 'utf-8')); 56 | } 57 | catch (e) { 58 | this.emit('error', e.message); 59 | } 60 | }; 61 | 62 | UMD.prototype.generate = function generate() { 63 | var options = this.options, 64 | code = this.code, 65 | ctx = objectMerge({}, options); 66 | 67 | var depsOptions = objectMerge( 68 | getDependencyDefaults(this.options.globalAlias), 69 | convertDependencyArrays(options.deps) || {} 70 | ); 71 | 72 | var defaultDeps = depsOptions['default'].items; 73 | var deps = defaultDeps ? defaultDeps || defaultDeps.items || [] : []; 74 | var dependency, dependencyType, items, prefix, separator, suffix; 75 | 76 | for (dependencyType in depsOptions) { 77 | dependency = depsOptions[dependencyType]; 78 | 79 | items = dependency.items || defaultDeps || []; 80 | 81 | // extract possible dependency names for objects 82 | items = items.map(function(item) { 83 | if(is.object(item)) { 84 | return Object.keys(item)[0]; 85 | } 86 | 87 | return item; 88 | }); 89 | 90 | prefix = dependency.prefix || ''; 91 | separator = dependency.separator || ', '; 92 | suffix = dependency.suffix || ''; 93 | 94 | ctx[dependencyType + 'Dependencies'] = { 95 | normal: items.map(function(item){ return 'root["' + item + '"]'; }), 96 | params: convertToAlphabet(items), 97 | wrapped: items.map(wrap(prefix, suffix)).join(separator), 98 | }; 99 | } 100 | 101 | // supports ['dependency'] and [{dependency: 'functionParameter'}] 102 | ctx.dependencies = deps.map(function(dep) { 103 | if(is.string(dep)) { 104 | return dep; 105 | } 106 | 107 | if(is.object(dep)) { 108 | return dep[Object.keys(dep)[0]]; 109 | } 110 | }).filter(id).join(', '); 111 | 112 | deps.join(', '); 113 | 114 | ctx.code = code; 115 | 116 | return this.template(ctx); 117 | }; 118 | 119 | function convertToAlphabet(items) { 120 | return items.map(function(_, i) { 121 | return alphabet[i] + i; 122 | }); 123 | } 124 | 125 | function wrap(pre, post) { 126 | pre = pre || ''; 127 | post = post || ''; 128 | 129 | return function (v) { 130 | return pre + v + post; 131 | }; 132 | } 133 | 134 | function convertDependencyArrays(deps) { 135 | if(!deps) { 136 | return; 137 | } 138 | 139 | return zip.toObject(zip(deps).map(function(pair) { 140 | if(is.array(pair[1])) { 141 | return [pair[0], { 142 | items: pair[1] 143 | }]; 144 | } 145 | 146 | return pair; 147 | })); 148 | } 149 | 150 | function getDependencyDefaults(globalAlias) { 151 | return { 152 | 'default': { 153 | items: null, 154 | }, 155 | amd: { 156 | items: null, 157 | prefix: '\"', 158 | separator: ',', 159 | suffix: '\"', 160 | }, 161 | cjs: { 162 | items: null, 163 | prefix: 'require(\"', 164 | separator: ',', 165 | suffix: '\")', 166 | }, 167 | global: { 168 | items: null, 169 | prefix: globalAlias? globalAlias + '.': '\"', 170 | separator: ',', 171 | suffix: '\"', 172 | } 173 | }; 174 | } 175 | 176 | module.exports = function(code, options) { 177 | var u = new UMD(code, options); 178 | 179 | return u.generate(); 180 | }; 181 | 182 | function id(a) {return a;} 183 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "libumd", 3 | "description": "Wraps given JavaScript code with UMD", 4 | "author": "Juho Vepsalainen ", 5 | "version": "0.9.0", 6 | "dependencies": { 7 | "alphabet": "^1.0.0", 8 | "annois": "^0.3.2", 9 | "annozip": "^0.2.6", 10 | "handlebars": "^4.0.2", 11 | "object-merge": "^2.5.1" 12 | }, 13 | "devDependencies": { 14 | "localeval": "^15.2.3", 15 | "phantom": "^3.0.3", 16 | "tmp": "0.0.30" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/bebraw/libumd.git" 21 | }, 22 | "homepage": "https://github.com/bebraw/libumd", 23 | "bugs": { 24 | "url": "https://github.com/bebraw/libumd/issues" 25 | }, 26 | "scripts": { 27 | "test": "node tests" 28 | }, 29 | "keywords": [ 30 | "umd" 31 | ], 32 | "license": "MIT" 33 | } 34 | -------------------------------------------------------------------------------- /templates/returnExportsGlobal.hbs: -------------------------------------------------------------------------------- 1 | {{!-- 2 | Uses Node, AMD or browser globals to create a module. This example creates 3 | a global even when AMD is used. This is useful if you have some scripts 4 | that are loaded by an AMD loader, but they still want access to globals. 5 | If you do not need to export a global for the AMD case, 6 | see returnExports.js. 7 | 8 | If you want something that will work in other stricter CommonJS environments, 9 | or if you need to create a circular dependency, see commonJsStrictGlobal.js 10 | 11 | Defines a module "returnExportsGlobal" that depends another module called 12 | "b". Note that the name of the module is implied by the file name. It is 13 | best if the file name and the exported global have matching names. 14 | 15 | If the 'b' module also uses this type of boilerplate, then 16 | in the browser, it will create a global .b that is used below. 17 | --}} 18 | 19 | (function (root, factory) { 20 | if (root === undefined && window !== undefined) root = window; 21 | if (typeof define === 'function' && define.amd) { 22 | {{! AMD. Register as an anonymous module. }} 23 | define({{#if amdModuleId}}'{{amdModuleId}}', {{/if}}[{{{amdDependencies.wrapped}}}], function ({{dependencies}}) { 24 | return ({{#if globalAlias}} root['{{{globalAlias}}}'] = {{/if}}factory({{dependencies}})); 25 | }); 26 | } else if (typeof module === 'object' && module.exports) { 27 | {{!-- 28 | Node. Does not work with strict CommonJS, but 29 | only CommonJS-like enviroments that support module.exports, 30 | like Node. 31 | --}} 32 | var module_exports = factory({{{cjsDependencies.wrapped}}}); 33 | module.exports = module_exports; 34 | 35 | {{! FIX FOR BROWSERIFY: Set global alias if we in browserify. }} 36 | {{#if globalAlias}} 37 | if(typeof window !== 'undefined'){ 38 | window['{{{globalAlias}}}'] = module_exports; 39 | } 40 | {{/if}} 41 | } else { 42 | {{! Browser globals }} 43 | {{#if globalAlias}}root['{{{globalAlias}}}'] = {{/if}}factory({{{globalDependencies.normal}}}); 44 | } 45 | }(this, function ({{dependencies}}) { 46 | 47 | {{{code}}} 48 | 49 | {{!-- 50 | Just return a value to define the module export. 51 | This example returns an object, but the module 52 | can return a function as the exported value. 53 | --}} 54 | 55 | return {{{objectToExport}}}; 56 | 57 | })); 58 | -------------------------------------------------------------------------------- /templates/umd+rails.hbs: -------------------------------------------------------------------------------- 1 | {{{pipelineDependencies}}} 2 | 3 | (function(factory) { 4 | /* jshint undef: true */ 5 | if (typeof define === 'function' && define.amd) { 6 | define({{#if amdModuleId}}'{{amdModuleId}}', {{/if}}[ 7 | {{{amdDependencies.wrapped}}} 8 | ], factory); 9 | } 10 | else if (typeof module === 'object' && module.exports) { 11 | module.exports = factory( 12 | {{{cjsDependencies.wrapped}}}); 13 | } 14 | else { 15 | factory({{{globalDependencies}}}); 16 | } 17 | }(function({{dependencies}}) { 18 | 19 | {{{code}}} 20 | {{#if objectToExport}} 21 | return {{{objectToExport}}}; 22 | {{/if}} 23 | })); -------------------------------------------------------------------------------- /templates/umd.hbs: -------------------------------------------------------------------------------- 1 | (function (root, factory) { 2 | if (root === undefined && window !== undefined) root = window; 3 | if (typeof define === 'function' && define.amd) { 4 | // AMD. Register as an anonymous module unless amdModuleId is set 5 | define({{#if amdModuleId}}'{{amdModuleId}}', {{/if}}[{{{amdDependencies.wrapped}}}], function ({{{amdDependencies.params}}}) { 6 | return ({{#if globalAlias}}root['{{{globalAlias}}}'] = {{else}}{{#if objectToExport}}root['{{{objectToExport}}}'] = {{/if}}{{/if}}factory({{{amdDependencies.params}}})); 7 | }); 8 | } else if (typeof module === 'object' && module.exports) { 9 | // Node. Does not work with strict CommonJS, but 10 | // only CommonJS-like environments that support module.exports, 11 | // like Node. 12 | module.exports = factory({{{cjsDependencies.wrapped}}}); 13 | } else { 14 | {{#if globalAlias}}root['{{{globalAlias}}}'] = {{else}}{{#if objectToExport}}root['{{{objectToExport}}}'] = {{/if}}{{/if}}factory({{{globalDependencies.normal}}}); 15 | } 16 | }(this, function ({{dependencies}}) { 17 | 18 | {{{code}}} 19 | {{#if objectToExport}} 20 | return {{{objectToExport}}}; 21 | {{/if}} 22 | 23 | })); 24 | -------------------------------------------------------------------------------- /templates/unit.hbs: -------------------------------------------------------------------------------- 1 | {{! UMD template that can be useful to wrap standalone CommonJS/Node modules}} 2 | (function(root, factory) { 3 | if (root === undefined && window !== undefined) root = window; 4 | if (typeof module === 'object' && module.exports) { 5 | module.exports = factory({{#if cjsDependencies.wrapped}}{{{cjsDependencies.wrapped}}}, {{/if}}require, exports, module); 6 | } 7 | else if(typeof define === 'function' && define.amd) { 8 | define({{#if amdModuleId}}'{{amdModuleId}}', {{/if}}[{{#if amdDependencies.wrapped}}{{{amdDependencies.wrapped}}}, {{/if}}'require', 'exports', 'module'], factory); 9 | } 10 | else { 11 | var req = function(id) {return root[id];}, 12 | exp = root, 13 | mod = {exports: exp}; 14 | {{#if globalAlias}}root['{{globalAlias}}'] = {{else}}{{#if objectToExport}}root['{{objectToExport}}'] = {{/if}}{{/if}}factory({{#if globalDependencies.normal}}{{{globalDependencies.normal}}}, {{/if}}req, exp, mod); 15 | } 16 | }(this, function({{#if dependencies}}{{dependencies}}, {{/if}}require, exports, module) { 17 | {{{code}}} 18 | return {{#if objectToExport}}{{objectToExport}}{{else}}module.exports{{/if}}; 19 | })); 20 | -------------------------------------------------------------------------------- /tests/amd-with-deps-and-alias.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var fs = require('fs'); 4 | var path = require('path'); 5 | var umdify = require('../'); 6 | var utils = require('./utils'); 7 | 8 | module.exports = function() { 9 | var amdLoaderPath = path.join(__dirname, 'amd_loader.js'); 10 | var code = fs.readFileSync(amdLoaderPath, { 11 | encoding: 'utf-8' 12 | }); 13 | 14 | utils.read(function(data) { 15 | code += umdify(data, { 16 | amdModuleId: 'test', 17 | globalAlias: 'test' 18 | }); 19 | 20 | utils.read(function(data) { 21 | code += umdify(data, { 22 | amdModuleId: 'testDeps', 23 | globalAlias: 'testDeps', 24 | deps: { 25 | 'default': [{'test': 'alias'}] 26 | } 27 | }); 28 | code += '\nrequire([\'test\'], function(test) {test();});'; 29 | 30 | utils.runInPhantom(code, function(msg) { 31 | console.log('amd-with-deps ok'); 32 | assert.equal(msg, 'executed'); 33 | }); 34 | }, 'with-deps-and-alias.js'); 35 | }, 'browser.js'); 36 | } 37 | -------------------------------------------------------------------------------- /tests/amd-with-deps.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var fs = require('fs'); 4 | var path = require('path'); 5 | var umdify = require('../'); 6 | var utils = require('./utils'); 7 | 8 | module.exports = function() { 9 | var amdLoaderPath = path.join(__dirname, 'amd_loader.js'); 10 | var code = fs.readFileSync(amdLoaderPath, { 11 | encoding: 'utf-8' 12 | }); 13 | 14 | utils.read(function(data) { 15 | code += umdify(data, { 16 | amdModuleId: 'test', 17 | globalAlias: 'test' 18 | }); 19 | 20 | utils.read(function(data) { 21 | code += umdify(data, { 22 | amdModuleId: 'testDeps', 23 | globalAlias: 'testDeps', 24 | deps: { 25 | 'default': ['test'] 26 | } 27 | }); 28 | code += '\nrequire([\'testDeps\'], function(testDeps) {/* testDeps(); */});'; 29 | 30 | utils.runInPhantom(code, function(msg) { 31 | console.log('amd-with-deps ok'); 32 | assert.equal(msg, 'executed'); 33 | }); 34 | }, 'with-deps.js'); 35 | }, 'browser.js'); 36 | } 37 | -------------------------------------------------------------------------------- /tests/amd.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var fs = require('fs'); 4 | var path = require('path'); 5 | var umdify = require('../'); 6 | var utils = require('./utils'); 7 | 8 | module.exports = function() { 9 | var amdLoaderPath = path.join(__dirname, 'amd_loader.js'); 10 | var code = fs.readFileSync(amdLoaderPath, { 11 | encoding: 'utf-8' 12 | }); 13 | 14 | utils.read(function(data) { 15 | code += umdify(data, { 16 | amdModuleId: 'test', 17 | globalAlias: 'test' 18 | }); 19 | 20 | code += '\nrequire([\'test\'], function(test) {test.test();});'; 21 | 22 | utils.runInPhantom(code, function(msg) { 23 | console.log('amd ok'); 24 | assert.equal(msg, 'executed'); 25 | }); 26 | }, 'amd.js'); 27 | } 28 | -------------------------------------------------------------------------------- /tests/amd_loader.js: -------------------------------------------------------------------------------- 1 | var modules = {}; 2 | 3 | window.define = function(name, deps, cb) { 4 | modules[name] = cb(); 5 | }; 6 | window.define.amd = true; 7 | 8 | window.require = function(deps, module) { 9 | module.apply(null, getModules(deps)); 10 | 11 | function getModules(names) { 12 | return names.map(function(name) { 13 | return modules[name]; 14 | }); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /tests/browser-with-deps-and-alias.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var umdify = require('../'); 4 | var utils = require('./utils'); 5 | 6 | var code; 7 | module.exports = function() { 8 | utils.read(function(data) { 9 | code = umdify(data, { 10 | globalAlias: 'test', 11 | }); 12 | 13 | utils.read(function(data) { 14 | code += umdify(data, { 15 | globalAlias: 'testDeps', 16 | deps: { 17 | 'default': [{'test':'alias'}] 18 | } 19 | }); 20 | 21 | code += '\nwindow.testDeps();'; 22 | 23 | utils.runInPhantom(code, function(msg) { 24 | console.log('browser-with-deps-and-alias ok'); 25 | assert.equal(msg, 'executed'); 26 | }); 27 | }, 'with-deps-and-alias.js'); 28 | 29 | }, 'browser.js'); 30 | } 31 | -------------------------------------------------------------------------------- /tests/browser-with-deps.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var umdify = require('../'); 4 | var utils = require('./utils'); 5 | 6 | var code; 7 | module.exports = function() { 8 | utils.read(function(data) { 9 | code = umdify(data, { 10 | globalAlias: 'test', 11 | }); 12 | 13 | utils.read(function(data) { 14 | code += umdify(data, { 15 | globalAlias: 'testDeps', 16 | deps: { 17 | 'default': ['test'] 18 | } 19 | }); 20 | 21 | code += '\nwindow.testDeps();'; 22 | 23 | utils.runInPhantom(code, function(msg) { 24 | console.log('browser-with-deps ok'); 25 | assert.equal(msg, 'executed'); 26 | }); 27 | }, 'with-deps.js'); 28 | 29 | }, 'browser.js'); 30 | } 31 | -------------------------------------------------------------------------------- /tests/browser.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var assert = require('assert'); 3 | var umdify = require('../'); 4 | var utils = require('./utils'); 5 | 6 | module.exports = function() { 7 | utils.read(function(data) { 8 | var code = umdify(data, { 9 | globalAlias: 'test' 10 | }); 11 | 12 | code += '\nwindow.test();'; 13 | 14 | utils.runInPhantom(code, function(msg) { 15 | console.log('browser ok'); 16 | assert.equal(msg, 'executed'); 17 | }); 18 | }, 'browser.js'); 19 | } 20 | -------------------------------------------------------------------------------- /tests/cjs.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var assert = require('assert'); 4 | var path = require('path'); 5 | 6 | var localeval = require('localeval'); 7 | 8 | var umdify = require('../'); 9 | 10 | var read = require('./utils').read; 11 | 12 | 13 | module.exports = function() { 14 | triggered({}); 15 | triggered(); 16 | 17 | okTemplateName(); 18 | invalidTemplateName(); 19 | 20 | okTemplatePath(); 21 | invalidTemplatePath(); 22 | 23 | useDefault(); 24 | preserveDefault(); 25 | 26 | convertParametersToAlphabet(); 27 | 28 | noCode(); 29 | 30 | console.log('cjs ok'); 31 | }; 32 | 33 | function triggered(options) { 34 | read(function(data) { 35 | var code = umdify(data, options); 36 | 37 | var triggered; 38 | localeval(code, { 39 | trigger: function() { 40 | triggered = true; 41 | } 42 | }); 43 | 44 | assert(triggered); 45 | }); 46 | } 47 | 48 | function okTemplateName() { 49 | read(function(data) { 50 | var code = umdify(data, { 51 | template: 'returnExportsGlobal' 52 | }); 53 | 54 | var triggered; 55 | localeval(code, { 56 | trigger: function() { 57 | triggered = true; 58 | } 59 | }); 60 | 61 | assert(triggered); 62 | }); 63 | } 64 | 65 | function invalidTemplateName() { 66 | read(function(data) { 67 | assert.throws(function() { 68 | umdify(data, { 69 | template: 'foobar' 70 | }); 71 | }, 72 | Error); 73 | }); 74 | } 75 | 76 | function okTemplatePath() { 77 | read(function(data) { 78 | var p = path.join(__dirname, '..', 'templates', 'umd.hbs'); 79 | 80 | var code = umdify(data, { 81 | template: p 82 | }); 83 | 84 | var triggered; 85 | localeval(code, { 86 | trigger: function() { 87 | triggered = true; 88 | } 89 | }); 90 | 91 | assert(triggered); 92 | }); 93 | } 94 | 95 | function invalidTemplatePath() { 96 | read(function(data) { 97 | var p = path.join(__dirname, '..', 'templates', 'foo'); 98 | 99 | assert.throws(function() { 100 | umdify(data, { 101 | template: p 102 | }); 103 | }, 104 | Error); 105 | }); 106 | } 107 | 108 | function useDefault() { 109 | var dep = 'foobar'; 110 | var code = umdify('foo()', { 111 | deps: { 112 | 'default': [dep], 113 | }, 114 | }); 115 | 116 | assert(code.indexOf('define(["' + dep + '"]') >= 0); 117 | assert(code.indexOf('factory(require("' + dep + '"))') >= 0); 118 | assert(code.indexOf('factory(root["' + dep + '"])') >= 0); 119 | } 120 | 121 | function preserveDefault() { 122 | var dep = 'foobar'; 123 | var code = umdify('foo()', { 124 | deps: { 125 | 'default': [dep], 126 | 'amd': ['baz', 'bar'], 127 | }, 128 | }); 129 | 130 | assert(code.indexOf('define(["baz","bar"], function (a0,b1) {') >= 0); 131 | assert(code.indexOf('factory(require("' + dep + '"))') >= 0); 132 | assert(code.indexOf('factory(root["' + dep + '"])') >= 0); 133 | } 134 | 135 | function convertParametersToAlphabet() { 136 | var code = umdify('foo()', { 137 | deps: { 138 | 'default': ['foobar'], 139 | 'amd': ['baz', 'bar'], 140 | }, 141 | }); 142 | 143 | assert(code.indexOf('a0,b1') >= 0); 144 | } 145 | 146 | function noCode() { 147 | assert.throws(function() { 148 | umdify(); 149 | }, function(err) { 150 | if(err instanceof Error) { 151 | return true; 152 | } 153 | }); 154 | } 155 | -------------------------------------------------------------------------------- /tests/data/amd.js: -------------------------------------------------------------------------------- 1 | return { 2 | test: function() { 3 | console.log('executed'); 4 | 5 | window.close(); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /tests/data/browser.js: -------------------------------------------------------------------------------- 1 | return function test() { 2 | console.log('executed'); 3 | 4 | window.close(); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/data/demo.js: -------------------------------------------------------------------------------- 1 | trigger(); 2 | -------------------------------------------------------------------------------- /tests/data/with-deps-and-alias.js: -------------------------------------------------------------------------------- 1 | return function testDeps() { 2 | alias(); 3 | 4 | window.close(); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/data/with-deps.js: -------------------------------------------------------------------------------- 1 | return function testDeps() { 2 | test(); 3 | 4 | window.close(); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var amd = require('./amd'); 3 | var amdWithDeps = require('./amd-with-deps'); 4 | var browser = require('./browser'); 5 | var browserWithDeps = require('./browser-with-deps'); 6 | var browserWithDepsAndAlias = require('./browser-with-deps-and-alias'); 7 | var cjs = require('./cjs'); 8 | 9 | tests(); 10 | 11 | function tests() { 12 | amd(); 13 | amdWithDeps(); 14 | browser(); 15 | browserWithDeps(); 16 | browserWithDepsAndAlias(); 17 | cjs(); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /tests/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | var fs = require('fs'); 3 | var path = require('path'); 4 | var tmp = require('tmp'); 5 | var phantom = require('phantom'); 6 | 7 | exports.read = function(cb, file) { 8 | var p = path.join(__dirname, 'data', file || 'demo.js'); 9 | 10 | fs.readFile(p, { 11 | encoding: 'utf-8' 12 | }, function(err, data) { 13 | if(err) { 14 | return console.error(err); 15 | } 16 | 17 | cb(data); 18 | }); 19 | }; 20 | 21 | exports.runInPhantom = function(code, consoleCb) { 22 | tmp.file(function(err, path, fd) { 23 | if(err) { 24 | return console.error(err); 25 | } 26 | 27 | fs.writeFile(path, code, function(err) { 28 | if(err) { 29 | return console.error(err); 30 | } 31 | 32 | var phInstance; 33 | 34 | phantom.create().then(function(instance) { 35 | phInstance = instance; 36 | 37 | return instance.createPage(); 38 | }).then(function(page) { 39 | page.property('onConsoleMessage', consoleCb); 40 | 41 | page.injectJs(path, function(ok) { 42 | if(!ok) { 43 | return console.error('Failed to inject js'); 44 | } 45 | }); 46 | 47 | return page; 48 | }).then(function() { 49 | phInstance.exit(); 50 | }).catch(function(err) { 51 | console.error(err); 52 | 53 | phInstance.exit(); 54 | }) 55 | }); 56 | }); 57 | }; 58 | --------------------------------------------------------------------------------