This repository has been archived by the owner on Aug 22, 2019. It is now read-only.
forked from jantimon/favicons-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (83 loc) · 2.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
'use strict';
var childCompiler = require('./lib/compiler.js');
var assert = require('assert');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
function FaviconsWebpackPlugin (options) {
if (typeof options === 'string') {
options = {logo: options};
}
assert(typeof options === 'object', 'FaviconsWebpackPlugin options are required');
assert(options.logo, 'An input file is required');
this.options = _.extend({
prefix: 'icons-[hash]/',
emitStats: false,
statsFilename: 'iconstats-[hash].json',
persistentCache: true,
inject: true,
background: '#fff'
}, options);
this.options.icons = _.extend({
android: true,
appleIcon: true,
appleStartup: true,
coast: false,
favicons: true,
firefox: true,
opengraph: false,
twitter: false,
yandex: false,
windows: false
}, this.options.icons);
}
FaviconsWebpackPlugin.prototype.apply = function (compiler) {
var self = this;
if (!self.options.title) {
self.options.title = guessAppName(compiler.context);
}
// Generate the favicons
var compilationResult;
compiler.plugin('make', function (compilation, callback) {
childCompiler.compileTemplate(self.options, compiler.context, compilation)
.then(function (result) {
compilationResult = result;
callback();
})
.catch(callback);
});
// Hook into the html-webpack-plugin processing
// and add the html
if (self.options.inject) {
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-before-html-processing', function (htmlPluginData, callback) {
if (htmlPluginData.plugin.options.favicons !== false) {
htmlPluginData.html = htmlPluginData.html.replace(
/(<\/head>)/i, compilationResult.stats.html.join('') + '$&');
}
callback(null, htmlPluginData);
});
});
}
// Remove the stats from the output if they are not required
if (!self.options.emitStats) {
compiler.plugin('emit', function (compilation, callback) {
delete compilation.assets[compilationResult.outputName];
callback();
});
}
};
/**
* Tries to guess the name from the package.json
*/
function guessAppName (compilerWorkingDirectory) {
var packageJson = path.resolve(compilerWorkingDirectory, 'package.json');
if (!fs.existsSync(packageJson)) {
packageJson = path.resolve(compilerWorkingDirectory, '../package.json');
if (!fs.existsSync(packageJson)) {
return 'Webpack App';
}
}
return JSON.parse(fs.readFileSync(packageJson)).name;
}
module.exports = FaviconsWebpackPlugin;