/
index.js
83 lines (76 loc) · 2.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
/* Middleware allows to export server commonjs modules to client side.
* using requriejs.
*/
var fs = require('fs'),
path = require('path');
/* Wrap commonjs files into requirejs code */
var amdWrapper = function(text) {
var useStrictRegExp = /^("|')use strict("|');/,
isGlobalUseStrict = useStrictRegExp.test(text);
text = text.replace(useStrictRegExp, '');
text =
(isGlobalUseStrict ? '\'use strict\';\n' : '\n') +
'\ndefine(function(require, exports, module) {\n' +
text +
'\n});\n';
return text;
};
/* Params structure:
* @param [String] basePath base output directory for project
* @param [String] baseUrl base url
* @param [Object] modules list of modules with key - url, that you use in requirejs
* - path: path to module file
*/
/* Build project from params */
module.exports.builder = function(params) {
var modules = params.modules,
url, text;
if (!params.basePath) {
throw new Error('Base path not defined');
}
if (modules && isObject(modules)) {
Object.keys(modules).forEach(function(key) {
if (!modules[key].path) {
throw new Error('Path for module ' + key + ' not defined');
}
text = amdWrapper(fs.readFileSync(modules[key].path + '.js', 'utf-8'));
fs.writeFileSync(path.join(params.basePath, key) + '.js', text);
});
} else {
throw new Error('No modules spicified');
}
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
};
/* Wraps all requested files in params */
module.exports.wrapper = function(params) {
params = params || {};
params.baseUrl = params.baseUrl || '';
return function(req, res, next) {
// remove query string, baseUrl and js extension
var url = req.url.replace(params.baseUrl, '').replace(/(\.js\?.+$)/, '');
var config = params.modules[url];
if (config) {
if (!config.path) {
next(new Error('Path for module ' + req.url + ' not defined'));
return;
}
fs.readFile(
config.path + '.js',
'utf-8',
function(err, text) {
if (err) {
next(err);
return;
}
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
res.end(amdWrapper(text));
}
);
} else {
next();
}
}
};