webpack中compilation.updateAsset的用法

首先贴出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方法返回资源大小

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值