-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.js
52 lines (47 loc) · 1.56 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
52
/**
* External dependencies
*/
const escapeStringRegexp = require( 'escape-string-regexp' );
/**
* Webpack plugin for handling specific template tags in Webpack configuration
* values like those supported in the base Webpack functionality (e.g. `name`).
*
* @see webpack.TemplatedPathPlugin
*/
class CustomTemplatedPathPlugin {
/**
* CustomTemplatedPathPlugin constructor. Initializes handlers as a tuple
* set of RegExp, handler, where the regular expression is used in matching
* a Webpack asset path.
*
* @param {Object.<string,Function>} handlers Object keyed by tag to match,
* with function value returning
* replacement string.
*/
constructor( handlers ) {
this.handlers = [];
for ( const [ key, handler ] of Object.entries( handlers ) ) {
const regexp = new RegExp( `\\[${ escapeStringRegexp( key ) }\\]`, 'gi' );
this.handlers.push( [ regexp, handler ] );
}
}
/**
* Webpack plugin application logic.
*
* @param {Object} compiler Webpack compiler
*/
apply( compiler ) {
compiler.hooks.compilation.tap( 'CustomTemplatedPathPlugin', ( compilation ) => {
compilation.mainTemplate.hooks.assetPath.tap( 'CustomTemplatedPathPlugin', ( path, data ) => {
for ( let i = 0; i < this.handlers.length; i++ ) {
const [ regexp, handler ] = this.handlers[ i ];
if ( regexp.test( path ) ) {
return path.replace( regexp, handler( path, data ) );
}
}
return path;
} );
} );
}
}
module.exports = CustomTemplatedPathPlugin;