UNPKG

1.35 kBJavaScriptView Raw
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
8// This Webpack plugin lets us interpolate custom variables into `index.html`.
9// Usage: `new InterpolateHtmlPlugin({ 'MY_VARIABLE': 42 })`
10// Then, you can use %MY_VARIABLE% in your `index.html`.
11
12// It works in tandem with HtmlWebpackPlugin.
13// Learn more about creating plugins like this:
14// https://github.com/ampedandwired/html-webpack-plugin#events
15
16'use strict';
17const escapeStringRegexp = require('escape-string-regexp');
18
19class InterpolateHtmlPlugin {
20 constructor(replacements) {
21 this.replacements = replacements;
22 }
23
24 apply(compiler) {
25 compiler.plugin('compilation', compilation => {
26 compilation.plugin(
27 'html-webpack-plugin-before-html-processing',
28 (data, callback) => {
29 // Run HTML through a series of user-specified string replacements.
30 Object.keys(this.replacements).forEach(key => {
31 const value = this.replacements[key];
32 data.html = data.html.replace(
33 new RegExp('%' + escapeStringRegexp(key) + '%', 'g'),
34 value
35 );
36 });
37 callback(null, data);
38 }
39 );
40 });
41 }
42}
43
44module.exports = InterpolateHtmlPlugin;