UNPKG

1.7 kBJavaScriptView Raw
1'use strict';
2
3var handlebars = require('handlebars');
4var path = require('path');
5var fs = require('fs');
6var xtend = require('xtend');
7
8var templatePath = path.join(__dirname, 'remote.hbs');
9var template = fs.readFileSync(templatePath, 'utf8');
10var remote = handlebars.compile(template);
11var genPath = path.join(__dirname, '..', 'loaders');
12
13function mapDeps(config) {
14 if (!config.deps) return config;
15 return xtend(config, {
16 deps: Object.keys(config.deps).map(function (k) {
17 return { key: k, global: config.deps[k] };
18 }),
19 });
20}
21
22/**
23 * Generates file that fetch the remote script asynchronously and call back with the object it exports
24 * Expected to be called during initialization and therefore uses sync IO
25 * TODO: make async and take array of configs to generate remotes for
26 * call back with list of paths of remotes
27 *
28 * @name genRemote
29 * @function
30 * @param {Object} config {
31 * key : {String} module name,
32 * deps : {[Object]} [ { depname : 'name under which to attach the dependency to global scope' }, ],
33 * exports : {String} name under which it is attached to the global scope,
34 * init : {Function} to to initialize the module
35 * }
36 * @param {Function} cb called back with error or path of generated file
37 */
38var genRemote = module.exports = function (config, cb) {
39 var name = config.key;
40 var opts = mapDeps(config);
41 opts.exportRemotePath = require.resolve('./export-remote');
42
43 var s = remote(opts);
44 var filePath = path.join(genPath, name + '.js');
45 fs.writeFile(filePath, s, 'utf8', function (err) {
46 if (err) return cb(err);
47 cb(null, filePath);
48 });
49};
50