Repository URL to install this package:
|
Version:
1.3.3 ▾
|
import * as path from 'path'
import {
Matchable,
Replacement,
Result,
Compiler,
NormalModuleFactory,
} from './typings'
const pluginName = 'NormalModuleReplacementPlugin'
export class ModuleReplacementOverridePlugin {
resourceRegExp: Matchable
newResource: Replacement
constructor(resourceRegExp: Matchable, newResource: Replacement) {
this.resourceRegExp = resourceRegExp
this.newResource = newResource
}
beforeResolve = (result: Result) => {
if (!result) {
return undefined
}
if (this.resourceRegExp.test(result.request)) {
if (typeof this.newResource === 'function') {
this.newResource(result)
} else {
result.request = this.newResource
}
}
return result
}
afterResolve = (result: Result) => {
if (!result) {
return undefined
}
if (this.resourceRegExp.test(result.resource)) {
if (typeof this.newResource === 'function') {
this.newResource(result)
} else {
result.resource = path.resolve(
path.dirname(result.resource),
this.newResource
)
}
}
return result
}
apply(compiler: Compiler): void {
compiler.hooks.normalModuleFactory.tap(
pluginName,
(normalModuleFactory: NormalModuleFactory) => {
normalModuleFactory.hooks.beforeResolve.tap(
pluginName,
this.beforeResolve
)
normalModuleFactory.hooks.afterResolve.tap(
pluginName,
this.afterResolve
)
}
)
}
}