Skip to content

Commit

Permalink
Merge pull request #254 from stereobooster/support-cra2-code-splitting-2
Browse files Browse the repository at this point in the history
Make sure that vendors chunk from CRA2 is preloaded first
  • Loading branch information
stereobooster committed Sep 7, 2018
2 parents 1e56ab2 + 7ca5b1c commit 45cfb2a
Showing 1 changed file with 29 additions and 8 deletions.
37 changes: 29 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,34 +357,53 @@ const asyncScriptTags = ({ page }) => {
});
};

const fixWebpackChunksIssue = ({ page, basePath, http2PushManifest }) => {
const fixWebpackChunksIssue = ({
page,
basePath,
http2PushManifest,
inlineCss
}) => {
return page.evaluate(
(basePath, http2PushManifest) => {
(basePath, http2PushManifest, inlineCss) => {
const localScripts = Array.from(document.scripts).filter(
x => x.src && x.src.startsWith(basePath)
);
// CRA v1|v2
const mainRegexp = /main\.[\w]{8}.js|main\.[\w]{8}\.chunk\.js/;
const mainScript = localScripts.filter(x => mainRegexp.test(x.src))[0];
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
const firstStyle = document.querySelector("style");

if (!mainScript) return;

const chunkRegexp = /(\w+)\.[\w]{8}\.chunk\.js/g;
const chunkRegexp = /(\w+)\.[\w]{8}(\.chunk)?\.js/g;
const chunkScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched && matched[1] !== "main" && matched[1] !== "vendors";
});

const mainScripts = localScripts.filter(x => {
const matched = chunkRegexp.exec(x.src);
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
chunkRegexp.lastIndex = 0;
return matched && (matched[1] === "main" || matched[1] === "vendors");
});

const createLink = x => {
if (http2PushManifest) return;
const linkTag = document.createElement("link");
linkTag.setAttribute("rel", "preload");
linkTag.setAttribute("as", "script");
linkTag.setAttribute("href", x.src.replace(basePath, ""));
document.head.appendChild(linkTag);
if (inlineCss) {
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
} else {
document.head.appendChild(linkTag);
}
};

createLink(mainScript);
mainScripts.map(x => createLink(x));
for (let i = chunkScripts.length - 1; i >= 0; --i) {
const x = chunkScripts[i];
if (x.parentElement && mainScript.parentNode) {
Expand All @@ -394,7 +413,8 @@ const fixWebpackChunksIssue = ({ page, basePath, http2PushManifest }) => {
}
},
basePath,
http2PushManifest
http2PushManifest,
inlineCss
);
};

Expand Down Expand Up @@ -588,7 +608,8 @@ const run = async (userOptions, { fs } = { fs: nativeFs }) => {
await fixWebpackChunksIssue({
page,
basePath,
http2PushManifest
http2PushManifest,
inlineCss: options.inlineCss
});
}
if (options.asyncScriptTags) await asyncScriptTags({ page });
Expand Down

0 comments on commit 45cfb2a

Please sign in to comment.