Skip to content

wikiwi/webpack-content-chunks

Repository files navigation

webpack-content-chunks

A solution for adding webpack content chunks to the server response.

NPM Version Widget Build Status Widget Coverage Status Widget

TOC

Installation

npm install webpack-content-chunks --save

Use Case

You already have an universal (isomorphic) app with server side rendering, routing, and code splitting using webpack. To avoid unnecessary round trips you want to optimize and include all content chunks to the server response.

Example

This is not a fully functional example and serves as a demonstration of the concept. It uses ES6 (webpack2), but would work with require, and require.ensure as well.

import * as fs from "fs";
import { WebpackContentChunks } from "webpack-content-chunks";

const stats = JSON.parse(fs.readFileSync("./stats.json", "utf8"));

function middleware(req, res) {
  const contentChunks = new WebpackContentChunks(stats);

  matchRoutes(req.url, contentChunks);
  matchMoreRoutes(req.url, contentChunks);

  const chunks = contentChunks.getFiles().filter(path => path.endsWith(".js"))
    .map(filename => `<script src="/${filename}" />`);

  res.send(`<html><body><script src="/main.js" />${chunks}</body></html>`);
}

function matchRoutes(url, contentChunks) {
  switch(url) {
    case "/home":
      // First code split in file.
      contentChunks.addChunksFrom(__filename, 0);
      System.import("./home").then(() => { /* ... */ });
      break;
    case "/contact":
      // Second code split in file.
      contentChunks.addChunksFrom(__filename, 1);
      System.import("./contact").then(() => { /* ... */ });
      break;
  }
}

function matchMoreRoutes(url, contentChunks) {
  switch(url) {
    case "/article":
      // Third code split in file.
      contentChunks.addChunksFrom(__filename, 2);
      Promise.all([System.import("./module1"), System.import("./module2")])
        .then(([module1, module2]) => { /* ... */ });
      break;
  }
}

How it works

webpack-content-chunks uses webpack stats to gather information about existing chunks. It then groups content chunks originating from the same line of code together as a single code split.

Troubleshooting

Where to get stats.json

Use the webpack-stats-plugin. We recommend the following config:

new StatsWriterPlugin({
  filename: "stats.json",
  fields: ["chunks"],
  transform: (data) => {
    const result = { chunks: [] };
    for (const c of data.chunks) {
      const entry = {
        files: c.files,
        origins: [],
      };
      for (const origin of c.origins) {
        delete origin.module;
        delete origin.moduleIdentifier;
        entry.origins.push(origin);
      }
      result.chunks.push(entry);
    }
    return JSON.stringify(result, null, 2);
  },
}),

If you are using the webpack-dev-middleware follow this instruction.

My stats.json is huge!

Use webpack-stats-plugin see where to get stats.json.

__filename always returns /index.js

It seems you are using webpack for you server side code. In this case you need to tell webpack to passthrough __filename.

node: {
  __filename: true,
}

API Reference

WebpackContentChunks

A class for adding content chunks and retrieving files from added chunks.

constructor(stats: Object)

Parameters

  • stats: Object - Webpack stats.

addChunksFrom(moduleName: string, codeSplit: number)

Adds all content chunks that originated from the nth-codesplit in given module.

Parameters

  • moduleName: string - Name of module, can be obtained using node's __filename feature.
  • codeSplit: number - Defines nth-codesplit starting at 0.

getFiles(): Array<string>

Returns an array of files from added chunks.

Returns: Array<string> - Array of files.

reset()

Resets instance as if no chunks has been added.

Contributions

Contributions welcome! Make sure to pass $ npm run test and run $ npm run docs when your changes affects the documentation.