InterpolateHtmlPlugin.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. // This webpack plugin lets us interpolate custom variables into `index.html`.
  8. // Usage: `new InterpolateHtmlPlugin(HtmlWebpackPlugin, { 'MY_VARIABLE': 42 })`
  9. // Then, you can use %MY_VARIABLE% in your `index.html`.
  10. // It works in tandem with HtmlWebpackPlugin.
  11. // Learn more about creating plugins like this:
  12. // https://github.com/ampedandwired/html-webpack-plugin#events
  13. 'use strict';
  14. const escapeStringRegexp = require('escape-string-regexp');
  15. class InterpolateHtmlPlugin {
  16. constructor(htmlWebpackPlugin, replacements) {
  17. this.htmlWebpackPlugin = htmlWebpackPlugin;
  18. this.replacements = replacements;
  19. }
  20. apply(compiler) {
  21. compiler.hooks.compilation.tap('InterpolateHtmlPlugin', compilation => {
  22. this.htmlWebpackPlugin
  23. .getHooks(compilation)
  24. .afterTemplateExecution.tap('InterpolateHtmlPlugin', data => {
  25. // Run HTML through a series of user-specified string replacements.
  26. Object.keys(this.replacements).forEach(key => {
  27. const value = this.replacements[key];
  28. data.html = data.html.replace(
  29. new RegExp('%' + escapeStringRegexp(key) + '%', 'g'),
  30. value
  31. );
  32. });
  33. });
  34. });
  35. }
  36. }
  37. module.exports = InterpolateHtmlPlugin;