Skip to content

Instantly share code, notes, and snippets.

@ZKHelloworld
Last active June 10, 2021 03:38
Show Gist options
  • Save ZKHelloworld/5d8353ee602982c1ccc3b934b411108e to your computer and use it in GitHub Desktop.
Save ZKHelloworld/5d8353ee602982c1ccc3b934b411108e to your computer and use it in GitHub Desktop.
async-jsonp-webpack-plugin
const { RawSource, CachedSource } = require('webpack').sources;
const Compilation = require('webpack').Compilation;
const PLUGIN_NAME = 'AsyncJsonpWebpackPlugin';
/**
* modify webpack output to async jsonp
*
* before:
* (() => {
* // sync code run
* })()
*
* after:
* webpack.config.js
* const AsyncJsonpWebpackPlugin = new AsyncJsonpWebpackPlugin({
* jsonp: "GlobalAsyncRegistry('button', '1.0.0')"
* })
* {
* output: asyncJsonpWebpackPlugin.injectOutput({ ... }),
* plugins: [
* asyncJsonpWebpackPlugin
* ]
* }
*
* GlobalAsyncRegistry('button', '1.0.0')(() => (() => {
* // async code run
* })())
*/
class AsyncJsonpWebpackPlugin {
constructor(options) {
this.jsonp = options.jsonp;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE
},
(assets) => {
const outputAssets = assets[this.filename];
if (!outputAssets) {
callback();
return;
}
const outputContent = outputAssets.source();
// AsyncJsonpWebpackPlugin(
// =>
// ${jsonp}(() =>
let destContent = outputContent.replace(`${PLUGIN_NAME}(`, `${this.jsonp}(()=>`);
assets[this.filename] = new CachedSource(new RawSource(destContent));
}
);
});
}
/**
* change output to library jsonp mode
*
* @param {*} output
*/
injectOutput(output = {}) {
this.filename = output.filename;
const library = output.library || {};
return {
...output,
library: {
...library,
type: 'jsonp',
name: PLUGIN_NAME
}
};
}
}
module.exports = AsyncJsonpWebpackPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment