首先贴出updateAsset的源码:
/**
* @param {string} file file name
* @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new
* @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new
*/
updateAsset(
file,
newSourceOrFunction,
assetInfoUpdateOrFunction = undefined
) {
if (!this.assets[file]) {
throw new Error(
`Called Compilation.updateAsset for not existing filename ${file}`
);
}
if (typeof newSourceOrFunction === "function") {
this.assets[file] = newSourceOrFunction(this.assets[file]);
} else {
this.assets[file] = newSourceOrFunction;
}
if (assetInfoUpdateOrFunction !== undefined) {
const oldInfo = this.assetsInfo.get(file) || EMPTY_ASSET_INFO;
if (typeof assetInfoUpdateOrFunction === "function") {
this._setAssetInfo(file, assetInfoUpdateOrFunction(oldInfo), oldInfo);
} else {
this._setAssetInfo(
file,
cachedCleverMerge(oldInfo, assetInfoUpdateOrFunction),
oldInfo
);
}
}
}
再贴出 newSourceOrFunction 参数的类型:
/**
* Base class for all sources.
* A Source can be asked for source code, size, source map and hash.
*/
declare abstract class Source {
/**
* Returns the represented source code as string.
*/
source(): string | ArrayBuffer;
/**
* Returns the represented source code as Buffer. Strings are converted to utf-8.
*/
buffer(): Buffer;
/**
* Returns the size in chars of the represented source code.
*/
size(): number;
/**
* Returns the SourceMap of the represented source code as JSON.
* May return `null` if no SourceMap is available.
*/
map(options?: MapOptions): RawSourceMap | null;
/**
* Returns both, source code (like `Source.prototype.source()` and SourceMap (like `Source.prototype.map()`).
* This method could have better performance than calling `source()` and `map()` separately.
*/
sourceAndMap(options?: MapOptions): SourceAndMapResult;
/**
* Updates the provided Hash object with the content of the represented source code.
* (Hash is an object with an update method, which is called with string values)
*/
updateHash(hash: Hash): void;
}
再贴出调用方法
class BannerWebpackPlugin {
constructor(options = {}) {
this.options = options
}
apply(compiler) {
compiler.hooks.emit.tap('BannerWebpackPlugin', (compilation) => {
// 获取全部资源文件
const assets = compilation.getAssets()
// 代码前缀
const prefix = `/**
* @Author ${this.options.author}
*/
`
assets.forEach(asset => {
// 遍历获取到js文件
if (asset.name.endsWith('.js')) {
const content = prefix + asset.source._source._value
compilation.updateAsset(asset.name, {
source() {
return content
},
size() {
return content.length
}
})
}
})
})
}
}
module.exports = BannerWebpackPlugin
这里写了个创建js文件代码banner的插件,调用的时候只需要传入一个资源名称,和一个有source和size方法的对象,source方法需要返回资源内容,size方法返回资源大小