-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
227 lines (179 loc) · 5.99 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
var RawSource = require('webpack-sources/lib/RawSource');
var evaluate = require('eval');
var path = require('path');
var cheerio = require('cheerio');
var url = require('url');
var Promise = require('bluebird');
function StaticSiteGeneratorWebpackPlugin(options) {
if (arguments.length > 1) {
options = legacyArgsToOptions.apply(null, arguments);
}
options = options || {};
this.entry = options.entry;
this.paths = Array.isArray(options.paths) ? options.paths : [options.paths || '/'];
this.locals = options.locals;
this.globals = options.globals;
this.crawl = Boolean(options.crawl);
}
StaticSiteGeneratorWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('this-compilation', function(compilation) {
compilation.plugin('optimize-assets', function(_, done) {
var renderPromises;
var webpackStats = compilation.getStats();
var webpackStatsJson = webpackStats.toJson();
try {
var asset = findAsset(self.entry, compilation, webpackStatsJson);
if (asset == null) {
throw new Error('Source file not found: "' + self.entry + '"');
}
var assets = getAssetsFromCompilation(compilation, webpackStatsJson);
var source = asset.source();
var render = evaluate(source, /* filename: */ self.entry, /* scope: */ self.globals, /* includeGlobals: */ true);
if (render.hasOwnProperty('default')) {
render = render['default'];
}
if (typeof render !== 'function') {
throw new Error('Export from "' + self.entry + '" must be a function that returns an HTML string. Is output.libraryTarget in the configuration set to "umd"?');
}
renderPaths(self.crawl, self.locals, self.paths, render, assets, webpackStats, compilation)
.nodeify(done);
} catch (err) {
compilation.errors.push(err.stack);
done();
}
});
});
};
function renderPaths(crawl, userLocals, paths, render, assets, webpackStats, compilation) {
var renderPromises = paths.map(function(outputPath) {
var locals = {
path: outputPath,
assets: assets,
webpackStats: webpackStats
};
for (var prop in userLocals) {
if (userLocals.hasOwnProperty(prop)) {
locals[prop] = userLocals[prop];
}
}
var renderPromise = render.length < 2 ?
Promise.resolve(render(locals)) :
Promise.fromNode(render.bind(null, locals));
return renderPromise
.then(function(output) {
var outputByPath = typeof output === 'object' ? output : makeObject(outputPath, output);
var assetGenerationPromises = Object.keys(outputByPath).map(function(key) {
var rawSource = outputByPath[key];
var assetName = pathToAssetName(key);
if (compilation.assets[assetName]) {
return;
}
compilation.assets[assetName] = new RawSource(rawSource);
if (crawl) {
var relativePaths = relativePathsFromHtml({
source: rawSource,
path: key
});
return renderPaths(crawl, userLocals, relativePaths, render, assets, webpackStats, compilation);
}
});
return Promise.all(assetGenerationPromises);
})
.catch(function(err) {
compilation.errors.push(err.stack);
});
});
return Promise.all(renderPromises);
}
var findAsset = function(src, compilation, webpackStatsJson) {
if (!src) {
var chunkNames = Object.keys(webpackStatsJson.assetsByChunkName);
src = chunkNames[0];
}
var asset = compilation.assets[src];
if (asset) {
return asset;
}
var chunkValue = webpackStatsJson.assetsByChunkName[src];
if (!chunkValue) {
return null;
}
// Webpack outputs an array for each chunk when using sourcemaps
if (chunkValue instanceof Array) {
// Is the main bundle always the first element?
chunkValue = chunkValue[0];
}
return compilation.assets[chunkValue];
};
// Shamelessly stolen from html-webpack-plugin - Thanks @ampedandwired :)
var getAssetsFromCompilation = function(compilation, webpackStatsJson) {
var assets = {};
for (var chunk in webpackStatsJson.assetsByChunkName) {
var chunkValue = webpackStatsJson.assetsByChunkName[chunk];
// Webpack outputs an array for each chunk when using sourcemaps
if (chunkValue instanceof Array) {
// Is the main bundle always the first element?
chunkValue = chunkValue[0];
}
if (compilation.options.output.publicPath) {
chunkValue = compilation.options.output.publicPath + chunkValue;
}
assets[chunk] = chunkValue;
}
return assets;
};
function pathToAssetName(outputPath) {
var outputFileName = outputPath.replace(/^(\/|\\)/, ''); // Remove leading slashes for webpack-dev-server
if (!/\.(html?)$/i.test(outputFileName)) {
outputFileName = path.join(outputFileName, 'index.html');
}
return outputFileName;
}
function makeObject(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
function relativePathsFromHtml(options) {
var html = options.source;
var currentPath = options.path;
var $ = cheerio.load(html);
var linkHrefs = $('a[href]')
.map(function(i, el) {
return $(el).attr('href');
})
.get();
var iframeSrcs = $('iframe[src]')
.map(function(i, el) {
return $(el).attr('src');
})
.get();
return []
.concat(linkHrefs)
.concat(iframeSrcs)
.map(function(href) {
if (href.indexOf('//') === 0) {
return null
}
var parsed = url.parse(href);
if (parsed.protocol || typeof parsed.path !== 'string') {
return null;
}
return parsed.path.indexOf('/') === 0 ?
parsed.path :
url.resolve(currentPath, parsed.path);
})
.filter(function(href) {
return href != null;
});
}
function legacyArgsToOptions(entry, paths, locals, globals) {
return {
entry: entry,
paths: paths,
locals: locals,
globals: globals
};
}
module.exports = StaticSiteGeneratorWebpackPlugin;