-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.js
374 lines (318 loc) · 13.6 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* @file webpack-concat-plugin
* @author huangxueliang
*/
const fs = require('fs');
const Concat = require('concat-with-sourcemaps');
const UglifyJS = require('uglify-es');
const createHash = require('crypto').createHash;
const path = require('path');
const upath = require('upath');
const globby = require('globby');
const validateOptions = require('schema-utils');
const schema = require('./schema.json');
class ConcatPlugin {
constructor(options) {
options = Object.assign({
uglify: false,
sourceMap: false,
fileName: '[name].js',
name: 'result',
injectType: 'prepend',
outputPath: ''
}, options);
if (!options.filesToConcat || !options.filesToConcat.length) {
throw new Error('webpackConcatPlugin: option filesToConcat is required and should not be empty');
}
validateOptions(schema, options, 'webpackConcatPlugin');
options.outputPath = options.outputPath && this.ensureTrailingSlash(options.outputPath);
this.settings = options;
// used to determine if we should emit files during compiler emit event
this.startTime = Date.now();
this.prevTimestamps = {};
this.needCreateNewFile = true;
}
ensureTrailingSlash(string) {
if (string.length && string.substr(-1, 1) !== '/') {
return `${string}/`;
}
return string;
}
getFileName(files, filePath = this.settings.fileName) {
if (!this.needCreateNewFile) {
return this.finalFileName;
}
const fileRegExp = /\[name\]/;
const hashRegExp = /\[hash(?:(?::)([\d]+))?\]/;
if (this.settings.useHash || hashRegExp.test(filePath)) {
const fileHash = this.hashFile(files);
if (!hashRegExp.test(filePath)) {
filePath = filePath.replace(/\.js$/, '.[hash].js');
}
const regResult = hashRegExp.exec(filePath);
const hashLength = regResult[1] ? Number(regResult[1]) : fileHash.length;
filePath = filePath.replace(hashRegExp, fileHash.slice(0, hashLength));
}
return filePath.replace(fileRegExp, this.settings.name);
}
hashFile(files) {
if (this.fileHash && !this.needCreateNewFile) {
return this.fileHash;
}
const content = Object.keys(files)
.reduce((fileContent, fileName) => (fileContent + files[fileName]), '');
const { hashFunction = 'md5', hashDigest = 'hex' } = this.settings;
this.fileHash = createHash(hashFunction).update(content).digest(hashDigest);
if (hashDigest === 'base64') {
// these are not safe url characters.
this.fileHash = this.fileHash.replace(/[/+=]/g, (c) => {
switch (c) {
case '/': return '_';
case '+': return '-';
case '=': return '';
default: return c;
}
});
}
return this.fileHash;
}
getRelativePathAsync(context) {
return Promise.all(this.settings.filesToConcat.map(f => {
if (globby.hasMagic(f)) {
return globby(f, {
cwd: context,
nodir: true
});
}
return f;
})).then(rawResult =>
rawResult.reduce((target, resource) => target.concat(resource), [])
)
.catch(e => {
console.error(e);
});
}
resolveReadFiles(compiler) {
const self = this;
let readFilePromise;
const relativePathArrayPromise = this.getRelativePathAsync(compiler.options.context);
this.filesToConcatAbsolutePromise = new Promise((resolve, reject) => {
compiler.resolverFactory.plugin('resolver normal', resolver => {
resolve(relativePathArrayPromise
.then(relativeFilePathArray =>
Promise.all(relativeFilePathArray.map(relativeFilePath =>
new Promise((resolve, reject) =>
resolver.resolve(
{},
compiler.options.context,
relativeFilePath,
{},
(err, filePath) => {
if (err) {
reject(err);
}
else {
resolve(filePath);
}
}
)
)
))
).catch(e => {
console.error(e);
})
);
});
});
const createNewPromise = () => {
self.needCreateNewFile = true;
return this.filesToConcatAbsolutePromise
.then(filePathArray =>
Promise.all(filePathArray.map(
filePath => new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) {
reject(err);
}
else {
resolve({
['webpack:///' + upath.relative(compiler.options.context, filePath)]: data.toString()
});
}
});
})
))
).catch(e => {
console.error(e);
});
};
this.getReadFilePromise = createNew => {
if (!readFilePromise || createNew) {
readFilePromise = createNewPromise();
}
return readFilePromise;
};
}
resolveConcatAndUglify(compilation, files) {
const allFiles = files.reduce((file1, file2) => Object.assign(file1, file2), {});
let content = '';
let mapContent = '';
this.finalFileName = this.getFileName(allFiles);
const fileBaseName = path.basename(this.finalFileName);
if (this.settings.uglify) {
let options = {};
if (typeof this.settings.uglify === 'object') {
options = Object.assign({}, this.settings.uglify, options);
}
if (this.settings.sourceMap) {
options.sourceMap = {
url: `${fileBaseName}.map`,
includeSources: true
};
}
const result = UglifyJS.minify(allFiles, options);
if (result.error) {
throw result.error;
}
content = result.code;
if (this.settings.sourceMap) {
mapContent = result.map.toString();
}
}
else {
const concat = new Concat(!!this.settings.sourceMap, this.finalFileName, '\n');
Object.keys(allFiles).forEach(fileName => {
concat.add(fileName, allFiles[fileName]);
});
content = concat.content.toString();
if (this.settings.sourceMap) {
content += `//# sourceMappingURL=${fileBaseName}.map`;
mapContent = concat.sourceMap;
}
}
compilation.assets[`${this.settings.outputPath}${this.finalFileName}`] = {
source() {
return content;
},
size() {
return content.length;
}
};
compilation.hooks.moduleAsset.call({
userRequest: `${this.settings.outputPath}${this.settings.name}.js`
}, `${this.settings.outputPath}${this.finalFileName}`);
if (this.settings.sourceMap) {
compilation.assets[`${this.settings.outputPath}${this.finalFileName}.map`] = {
source() {
return mapContent;
},
size() {
return mapContent.length;
}
};
compilation.hooks.moduleAsset.call({
userRequest: `${this.settings.outputPath}${this.settings.name}.js.map`
}, `${this.settings.outputPath}${this.finalFileName}.map`);
}
this.needCreateNewFile = false;
}
apply(compiler) {
// ensure only compile one time per emit
let compileLoopStarted = false;
this.resolveReadFiles(compiler);
const self = this;
const dependenciesChanged = (compilation, filesToConcatAbsolute) => {
const fileTimestampsKeys = Object.keys(compilation.fileTimestamps);
// Since there are no time stamps, assume this is the first run and emit files
if (!fileTimestampsKeys.length) {
return true;
}
const changed = fileTimestampsKeys.filter(watchfile =>
(self.prevTimestamps[watchfile] || self.startTime) < (compilation.fileTimestamps[watchfile] || Infinity)
).some(f => filesToConcatAbsolute.includes(f));
this.prevTimestamps = compilation.fileTimestamps;
return changed;
};
const processCompiling = (compilation, callback) => {
self.filesToConcatAbsolutePromise.then(filesToConcatAbsolute => {
for (const f of filesToConcatAbsolute) {
compilation.fileDependencies.add(path.relative(compiler.options.context, f));
}
if (!dependenciesChanged(compilation, filesToConcatAbsolute)) {
return callback();
}
return self.getReadFilePromise(true).then(files => {
self.resolveConcatAndUglify(compilation, files);
callback();
});
}).catch(e => {
console.error(e);
});
};
compiler.hooks.compilation.tap('webpackConcatPlugin', compilation => {
let assetPath;
compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration
&& compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync('webpackConcatPlugin', (htmlPluginData, callback) => {
const getAssetPath = () => {
if (typeof self.settings.publicPath === 'undefined') {
if (typeof compilation.options.output.publicPath === 'undefined') {
return path.relative(path.dirname(htmlPluginData.outputName), `${self.settings.outputPath}${self.finalFileName}`);
}
return `${self.ensureTrailingSlash(compilation.options.output.publicPath)}${self.settings.outputPath}${self.finalFileName}`;
}
if (self.settings.publicPath === false) {
return path.relative(path.dirname(htmlPluginData.outputName), `${self.settings.outputPath}${self.finalFileName}`);
}
return `${self.ensureTrailingSlash(self.settings.publicPath)}${self.settings.outputPath}${self.finalFileName}`;
};
const injectToHtml = () => {
htmlPluginData.assets.webpackConcat = htmlPluginData.assets.webpackConcat || {};
assetPath = getAssetPath();
htmlPluginData.assets.webpackConcat[self.settings.name] = assetPath;
if (self.settings.injectType === 'prepend') {
htmlPluginData.assets.js.unshift(assetPath);
}
else if (self.settings.injectType === 'append') {
htmlPluginData.assets.js.push(assetPath);
}
};
if (!self.finalFileName || !compileLoopStarted) {
compileLoopStarted = true;
processCompiling(compilation, () => {
injectToHtml();
callback(null, htmlPluginData);
});
}
else {
injectToHtml();
callback(null, htmlPluginData);
}
});
compilation.hooks.htmlWebpackPluginAlterAssetTags
&& compilation.hooks.htmlWebpackPluginAlterAssetTags.tap('webpackConcatPlugin', htmlPluginData => {
if (self.settings.injectType !== 'none') {
const tags = htmlPluginData.head.concat(htmlPluginData.body);
const resultTag = tags.filter(tag =>
tag.attributes.src === assetPath
);
if (resultTag && resultTag.length && self.settings.attributes) {
Object.assign(resultTag[0].attributes, self.settings.attributes);
}
}
});
});
compiler.hooks.emit.tapAsync('webpackConcatPlugin', (compilation, callback) => {
if (!compileLoopStarted) {
compileLoopStarted = true;
processCompiling(compilation, callback);
}
else {
callback();
}
});
compiler.hooks.afterEmit.tap('webpackConcatPlugin', compilation => {
compileLoopStarted = false;
});
}
}
module.exports = ConcatPlugin;