webpack/lib/web/JsonpChunkTemplatePlugin.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
const { ConcatSource } = require("webpack-sources");
const getEntryInfo = require("./JsonpHelpers").getEntryInfo;
/** @typedef {import("../Chunk")} Chunk */
2018-06-26 22:07:19 +08:00
/** @typedef {import("../ChunkTemplate")} ChunkTemplate */
/** @typedef {import("../Compilation")} Compilation */
2018-06-26 22:07:19 +08:00
class JsonpChunkTemplatePlugin {
/**
* @param {Compilation} compilation the compilation
*/
constructor(compilation) {
this.compilation = compilation;
}
2018-06-26 22:07:19 +08:00
/**
* @param {ChunkTemplate} chunkTemplate the chunk template
* @returns {void}
*/
apply(chunkTemplate) {
2018-02-25 09:00:20 +08:00
chunkTemplate.hooks.render.tap(
"JsonpChunkTemplatePlugin",
(modules, moduleTemplate, { chunk, chunkGraph }) => {
2018-02-25 09:00:20 +08:00
const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction;
const globalObject = chunkTemplate.outputOptions.globalObject;
const source = new ConcatSource();
const prefetchChunks = chunk.getChildIdsByOrders(chunkGraph).prefetch;
2018-02-25 09:00:20 +08:00
source.add(
2018-03-26 22:56:10 +08:00
`(${globalObject}[${JSON.stringify(
jsonpFunction
)}] = ${globalObject}[${JSON.stringify(
jsonpFunction
)}] || []).push([${JSON.stringify(chunk.ids)},`
2018-02-25 09:00:20 +08:00
);
source.add(modules);
const entries = getEntryInfo(chunkGraph, chunk);
2018-02-25 09:00:20 +08:00
if (entries.length > 0) {
source.add(`,${JSON.stringify(entries)}`);
} else if (prefetchChunks && prefetchChunks.length) {
source.add(`,0`);
2018-05-31 06:36:50 +08:00
}
if (prefetchChunks && prefetchChunks.length) {
source.add(`,${JSON.stringify(prefetchChunks)}`);
2018-02-25 09:00:20 +08:00
}
source.add("])");
return source;
}
2018-02-25 09:00:20 +08:00
);
2017-12-15 22:16:39 +08:00
chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => {
hash.update("JsonpChunkTemplatePlugin");
hash.update("4");
2017-11-08 18:32:05 +08:00
hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`);
hash.update(`${chunkTemplate.outputOptions.globalObject}`);
});
2018-06-26 22:07:19 +08:00
chunkTemplate.hooks.hashForChunk.tap(
"JsonpChunkTemplatePlugin",
(hash, chunk) => {
const chunkGraph = this.compilation.chunkGraph;
hash.update(JSON.stringify(getEntryInfo(chunkGraph, chunk)));
hash.update(
JSON.stringify(chunk.getChildIdsByOrders(chunkGraph).prefetch) || ""
);
2018-06-26 22:07:19 +08:00
}
);
}
}
module.exports = JsonpChunkTemplatePlugin;