-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.js
51 lines (45 loc) · 1.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
'use strict';
const fs = require('fs');
const path = require('path');
class HtmlWebpackHarddiskPlugin {
constructor (options) {
this.options = options || {};
this.outputPath = this.options.outputPath;
}
apply (compiler) {
compiler.hooks.compilation.tap('HtmlWebpackHarddisk', (compilation) => {
// HtmlWebPackPlugin 4.x
const HtmlWebpackPlugin = require('html-webpack-plugin');
const hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks.afterEmit.tapAsync('HtmlWebpackHarddisk', (htmlPluginData, callback) => {
this.writeAssetToDisk(compilation, htmlPluginData.plugin.options, htmlPluginData.outputName, callback);
});
});
}
/**
* Writes an asset to disk
*/
writeAssetToDisk (compilation, htmlWebpackPluginOptions, webpackHtmlFilename, callback) {
// Skip if the plugin configuration didn't set `alwaysWriteToDisk` to true
if (!htmlWebpackPluginOptions.alwaysWriteToDisk) {
return callback(null);
}
// Prepare the folder
const fullPath = path.resolve(this.outputPath || compilation.compiler.outputPath, webpackHtmlFilename);
const directory = path.dirname(fullPath);
fs.mkdir(directory, { recursive: true }, 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;
module.exports.HtmlWebpackHarddiskPlugin = HtmlWebpackHarddiskPlugin;