MyHtmlBeautifyWebpackPlugin.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @see {link: https://github.com/seeyoulater/html-beautify-webpack-plugin/blob/master/index.js}
  3. */
  4. const prettify = require('html-prettify');
  5. const HtmlWebpackPlugin = require('html-webpack-plugin');
  6. const WebpackError = require( 'webpack/lib/WebpackError.js' );
  7. import { Compiler, Compilation } from 'webpack';
  8. interface OptionsConfigHtml {
  9. end_with_newline: boolean,
  10. indent_inner_html: boolean,
  11. preserve_newlines: boolean,
  12. max_preserve_newlines: number,
  13. }
  14. interface OptionsConfig {
  15. indent_size: number,
  16. indent_with_tabs: boolean,
  17. html: OptionsConfigHtml
  18. }
  19. interface Options{
  20. config: OptionsConfig,
  21. replace: Array<string|RegExp>
  22. }
  23. interface HtmlWebpackPluginArgs{
  24. html: string,
  25. plugin: typeof HtmlWebpackPlugin,
  26. outputName: string
  27. }
  28. function htmlPluginDataFunction (pluginData: HtmlWebpackPluginArgs, options: Options, callback: (err:typeof WebpackError, arg1: HtmlWebpackPluginArgs) => void) {
  29. pluginData.html = prettify(
  30. options.replace.reduce( (res:string, item: string | RegExp) => res.replace( item instanceof RegExp ? new RegExp(item, 'gi') : item, '' ), pluginData.html )/*,
  31. options.config*/
  32. );
  33. callback(null, pluginData);
  34. }
  35. export default class MyHtmlBeautifyWebpackPlugin {
  36. apply(compiler: Compiler): void {
  37. const options: Options = {
  38. config: { // TODO: Remove it.
  39. indent_size: 4,
  40. indent_with_tabs: false,
  41. html: {
  42. end_with_newline: true,
  43. indent_inner_html: true,
  44. preserve_newlines: true,
  45. max_preserve_newlines: 0,
  46. }
  47. },
  48. replace: []
  49. };
  50. function tapAsyncCallback(pluginData: HtmlWebpackPluginArgs, callback: (err:typeof WebpackError, arg1: HtmlWebpackPluginArgs) => void ){
  51. return htmlPluginDataFunction (pluginData, options, callback);
  52. }
  53. function tapHookCallback(compilation: Compilation){
  54. return HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync( 'MyHtmlBeautifyWebpackPlugin', tapAsyncCallback );
  55. }
  56. compiler.hooks.compilation.tap( 'MyHtmlBeautifyWebpackPlugin', tapHookCallback );
  57. }
  58. }