-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
244 lines (217 loc) · 8.08 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
const gutil = require("gulp-util");
const path = require('path');
const through = require("through2");
const fs = require('fs');
const fse = require('fs-extra');
const chalk = require("chalk");
const requireReg = /require\(['"]([\w\d_\-\.\/]+)['"]\)/ig;
const dest_node_modules_dir_name = 'gwcn-modules';
let config = {
'gwcn-src': 'src',
'gwcn-dest': 'dist',
'gwcn-node_modules': '../node_modules',
'gwcn-log': false
};
const gwcn = {
cache: {
},
gulp: {
},
srcToDest: function(source) {
let temp = source.replace(this.currentDir, '');
temp = temp.replace(config['gwcn-src'], config['gwcn-dest']);
return path.join(this.currentDir, temp);
},
destToSrc: function(source) {
let temp = source.replace(this.currentDir, '');
temp = temp.replace(config['gwcn-dest'], config['gwcn-src']);
return path.join(this.currentDir, temp);
},
isFile(p) {
p = (typeof(p) === 'object') ? path.join(p.dir, p.base) : p;
if (!fs.existsSync(p)) {
return false;
}
return fs.statSync(p).isFile();
},
isDir(p) {
if (!fs.existsSync(p)) {
return false;
}
return fs.statSync(p).isDirectory();
},
currentDir: process.cwd(),
destDir: function() {
return path.join(this.currentDir, config['gwcn-dest']);
},
srcDir: function() {
return path.join(this.currentDir, config['gwcn-src']);
},
dest_node_modules_dir: function() {
return path.join(this.destDir(), dest_node_modules_dir_name);
},
src_node_modules_dir: function() {
return path.join(this.srcDir(), config['gwcn-node_modules']);
},
fixGlobalAndWindow: function(code) {
if (/global|window/.test(code)) {
code = "var global=window=require('gulp-wxa-copy-npm/global');" + code;
}
return code;
},
fixNPM: function(code) {
code = code.replace(/([\w\[\]a-d\.]+)\s*instanceof Function/g, function(matchs, word) {
return ' typeof ' + word + " ==='function' ";
});
code = code.replace(/'use strict';\n?/g, '');
if (/[^\w_]process\.\w/.test(code) && !/typeof process/.test(code)) {
code = `var process={};${code}`;
}
return code;
},
npmHack(filename, code) {
switch (filename) {
case 'lodash.js':
case '_global.js':
code = code.replace('Function(\'return this\')()', 'this');
break;
case '_html.js':
code = 'module.exports = false;';
break;
case '_microtask.js':
code = code.replace('if(Observer)', 'if(false && Observer)');
// IOS 1.10.2 Promise BUG
code = code.replace('Promise && Promise.resolve', 'false && Promise && Promise.resolve');
break;
}
return code;
},
copyNPMDeps: function(code, destPath, currentNodeSrcDir, isNPM) {
let err = null;
let dest_node_modules_dir = this.dest_node_modules_dir();
let destDir = path.parse(destPath).dir;
let libs = [];
let matchs = [];
code = this.fixGlobalAndWindow(code);
code.replace(requireReg, (match, lib) => {
libs.push(lib);
matchs.push(match);
});
for (let i = 0; i < libs.length; i++) {
let lib = libs[i];
let match = matchs[i];
if (err) {
break;
}
let ext = '';
let resolved = lib;
let dep;
let relative = '';
if (lib[0] === '.') { // require('./something'');
if (!isNPM) {
continue;
}
ext = '.js';
dep = path.join(currentNodeSrcDir, lib);
relative = '';
} else if (lib.indexOf('/') === -1 || lib.indexOf('/') === lib.length - 1) { // require('asset');
let pkg = this.getPkgConfig(lib, this.gulp.enc);
if (!pkg) {
err = new gutil.PluginError('gulp-wxa-copy-npm', 'Package not found:' + lib);
break;
}
ext = pkg.main || 'index.js';
if (pkg.browser && typeof pkg.browser === 'string') {
ext = pkg.browser;
}
if (ext.indexOf('./') == 0) {
ext = ext.replace('./', '');
}
ext = path.sep + ext;
dep = path.join(this.src_node_modules_dir(), lib);
relative = path.relative(destDir, dest_node_modules_dir);
} else { // require('babel-runtime/regenerator')
dep = path.join(this.src_node_modules_dir(), lib);
if (this.isDir(dep) && this.isFile(dep + path.sep + 'index.js')) {
ext = path.sep + 'index.js';
} else if (this.isFile(dep + '.js')) {
ext = '.js';
} else if (this.isFile(dep)) {
ext = '';
} else {
err = new gutil.PluginError('gulp-wxa-copy-npm', 'File not found:' + dep);
break;
}
relative = path.relative(destDir, dest_node_modules_dir);
}
resolved = path.join(relative, lib + ext);
if (lib != resolved) {
config['gwcn-log'] && gutil.log(`Replace file: ${destDir} depences: from(${chalk.cyan(lib)}) to(${chalk.cyan(resolved)})`);
}
let npmPathString = dep.endsWith(ext) ? dep : dep + ext;
let npmPath = path.parse(npmPathString);
let outPath = path.join(this.currentDir, config['gwcn-dest'], dest_node_modules_dir_name, npmPathString.replace(this.src_node_modules_dir(), ''));
config['gwcn-log'] && gutil.log(`Copy npm depences: from(${chalk.cyan(npmPathString)}) to(${chalk.cyan(outPath)}) ...`);
resolved = resolved.replace(new RegExp('\\' + path.sep, 'g'), '/'); //Fix #1
code = code.replace(match, `require('${resolved}')`);
if (this.cache[outPath]) {
continue;
}
let depCode = fs.readFileSync(npmPathString, {
encoding: this.gulp.enc
});
err = this.copyNPMDeps(depCode, outPath, npmPath.dir, true).err;
}
if (isNPM && !this.cache[destPath] && !err) {
code = this.npmHack(path.parse(destPath).base, code);
code = this.fixNPM(code);
code = this.doPlugins(code, destPath);
fse.outputFileSync(destPath, code, {
encoding: this.gulp.enc
});
this.cache[destPath] = true;
}
return {
code: code,
err: err
};
},
getPkgConfig(lib, enc) {
let pkg = fs.readFileSync(path.join(this.src_node_modules_dir(), lib, 'package.json'), enc);
try {
pkg = JSON.parse(pkg);
} catch (e) {
pkg = null;
}
return pkg;
},
doPlugins: function(depCode, destPath) {
let result = depCode;
let plugins = config.plugins;
if (config.plugins) {
for (let i = 0; i < plugins.length; i++) {
let plugin = plugins[i];
result = plugin(result, destPath, gwcn.gulp);
}
}
return result;
}
}
module.exports = function(options) {
config = Object.assign(config, options);
return through.obj(function(file, enc, callback) {
gwcn.gulp.file = file;
gwcn.gulp.enc = enc;
gwcn.gulp.callback = callback;
gwcn.cache = {};
let sourceCode = file._contents.toString(enc);
let {
err,
code
} = gwcn.copyNPMDeps(sourceCode, gwcn.srcToDest(file.path), gwcn.src_node_modules_dir(), false);
// let transformCode = gwcn.replaceNPMDeps(sourceCode, gwcn.srcToDest(file.path))
file._contents = new Buffer(code);
// err maybe null
callback(err, file);
});
}