npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

webpack-content-chunks

v0.1.6

Published

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

Downloads

9

Readme

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.