This repository has been archived by the owner on Feb 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (71 loc) · 2.25 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
'use strict'
/**
* https://github.com/teambition/gulp-rjs2
* Licensed under the MIT license.
*/
var fs = require('fs')
var gutil = require('gulp-util')
var through = require('through2')
var requirejs = require('requirejs')
var push = Array.prototype.push
module.exports = function rjs (options) {
var stream = through.obj()
var path = options.out
var comName = options.name
var comNamespace = options.componentNamespace
var excludeModules = []
options.out = function (string) {
if (comNamespace && options.exclude) {
options.exclude.forEach(function (ele) {
var filePath = options.baseUrl + ele + '.js'
var file = fs.readFileSync(filePath, 'utf8')
push.apply(excludeModules, matchFirstArray(file))
})
string = addNameSpaceForUMD(string)
}
stream.push(new gutil.File({
path: path,
contents: new Buffer(string)
}))
}
requirejs.optimize(options, function (data) {
stream.push(null)
}, function (err) {
console.error(err)
stream.emit('error', err)
})
function addNameSpaceForUMD (string) {
return string
.replace(/\bdefine\(\s?['"](\S+?)['"]/g, function (match, p1) {
// AMD Define
if (!~excludeModules.indexOf(p1)) {
return match.replace(p1, p1 === comName ? comNamespace : (comNamespace + '.' + p1))
}
})
.replace(/\bdefine\([^\(]*?\[(.+?)\]/g, function (match, p1) {
// AMD Deps
var excludeModulesWithAMD = excludeModules.concat(['require', 'exports', 'module'])
return match.replace(p1, p1.replace(/['"](\S+?)['"]/g, function (match, p1) {
return match.replace(p1, !~excludeModulesWithAMD.indexOf(p1) ? (comNamespace + '.' + p1) : p1)
}))
})
.replace(/\brequire\(\s?['"](\S+?)['"]\)/g, function (match, p1) {
// CMD Require
if (!~excludeModules.indexOf(p1)) {
return match.replace(p1, comNamespace + '.' + p1)
}
})
}
function matchFirstArray (file) {
var reg = /\bdefine\(\s?[^\(]*?(\[.+?\])/
var matchValue = file.match(reg)
if (matchValue) {
// Convert string to array
matchValue = JSON.parse(matchValue[1].replace(/'/g, '"'))
} else {
matchValue = []
}
return matchValue
}
return stream
}