forked from jantimon/html-webpack-harddisk-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (60 loc) · 2.28 KB
/
index.js
File metadata and controls
66 lines (60 loc) · 2.28 KB
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
'use strict';
var mkdirp = require('mkdirp');
var fs = require('fs');
var path = require('path');
function HtmlWebpackHarddiskPlugin (options) {
options = options || {};
this.outputPath = options.outputPath;
}
HtmlWebpackHarddiskPlugin.prototype.apply = function (compiler) {
var self = this;
if (compiler.hooks) {
// webpack 4 support
compiler.hooks.compilation.tap('HtmlWebpackHarddisk', function (compilation) {
if (compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration) {
compilation.hooks.htmlWebpackPluginAfterEmit.tapAsync('HtmlWebpackHarddisk', function (htmlPluginData, callback) {
self.writeAssetToDisk(compilation, htmlPluginData.plugin.options, htmlPluginData.outputName, callback);
});
} else {
// HtmlWebPackPlugin 4.x
var HtmlWebpackPlugin = require('html-webpack-plugin');
var hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks.afterEmit.tapAsync('HtmlWebpackHarddisk', function (htmlPluginData, callback) {
self.writeAssetToDisk(compilation, htmlPluginData.plugin.options, htmlPluginData.outputName, callback);
});
}
});
} else {
// webpack 3 support
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (htmlPluginData, callback) {
self.writeAssetToDisk(compilation, htmlPluginData.plugin.options, htmlPluginData.outputName, callback);
});
});
}
};
/**
* Writes an asset to disk
*/
HtmlWebpackHarddiskPlugin.prototype.writeAssetToDisk = function (compilation, htmlWebpackPluginOptions, webpackHtmlFilename, callback) {
// Skip if the plugin configuration didn't set `alwaysWriteToDisk` to true
if (!htmlWebpackPluginOptions.alwaysWriteToDisk) {
return callback(null);
}
// Prepare the folder
var fullPath = path.resolve(this.outputPath || compilation.compiler.outputPath, webpackHtmlFilename);
var directory = path.dirname(fullPath);
mkdirp(directory, function (err) {
if (err) {
return callback(err);
}
// Write to disk
fs.writeFile(fullPath, compilation.assets[webpackHtmlFilename].source(), function (err) {
if (err) {
return callback(err);
}
callback(null);
});
});
};
module.exports = HtmlWebpackHarddiskPlugin;