react-loadable icon indicating copy to clipboard operation
react-loadable copied to clipboard

Adds `webpackReport` prop/function

Open leebenson opened this issue 6 years ago • 1 comments

This PR adds a webpackReport function alongside the existing report function to <Loadable.Capture>, to return module IDs via calls to require.resolveWeak()

Unlike module names, IDs act as a unique identifier for chunks (note: I've tested this for Webpack 4; I'm not sure if the Webpack 3 stats API/JSON dump is different... possibly due to the SplitChunksPlugin vs. CommonChunks, but I'm not sure.)

Assuming access to both client and server webpack stats in SSR middleware, this makes it trivial to cross-reference chunk identifiers and avoid edge cases where relative module names are identical, yet reference different chunks. An example might be having, say, a "./content" import which is different for every parent component; report can't distinguish between, but the above approach can.

Given SSR module capturing that looks something like this:

const components = (
  <Loadable.Capture
    report={(moduleName: string) => modules.push(moduleName)}
    webpackReport={(moduleName: string) => webpackModules.push(moduleName)}>
    <StaticRouter location={ctx.request.url} context={routeContext}>
      <Root />
    </StaticRouter>
  </Loadable.Capture>
);

... the relevant client-side chunks can be located like this:

const chunks = [].concat(
  ...webpackModules
    .map(moduleId => (
      [].concat(
        ...clientStats.modules
        .find((m: any) => m.identifier === serverStats.modules[moduleId].identifier).chunks
        .filter((m: any) => m /* filter for truthy values */)
        .map((c: any) => clientStats.chunks[c].files)
      ) 
    ))
);

const js = chunks.filter((c: string) => c.endsWith(".js"));

console.log("js -> ", js); // <--- DUMP OUT THE .JS SCRIPTS

... resulting in something like:

js -> [ 'assets/js/1.eb4231d455a06b1e155c.js', 'assets/js/4.a60aba1bbe9940e49e91.js' ]

Which can then be included in the HTML render.

leebenson avatar Mar 07 '18 14:03 leebenson

Could this be written as an additional argument to report(moduleName, webpackId)?

Also please remove the package-lock.json that was added in this PR

jamiebuilds avatar Feb 28 '20 22:02 jamiebuilds