Roots Discourse

Sage 9 Code Splitting

Howdy!

I’ve encountered a scenario where Sage 9’s “route-based” approach for page-specific JS doesn’t quite fit the bill.

One of the pages in my WP site pulls in a lot of external deps (I’m building something on top of PDF.js, which is a hefty library). Trouble is, if I include that page in my Router instance, the resulting bundle is massive (> 1mb). Ideally, other pages shouldn’t have to load that Javascript, since this functionality is isolated to a very specific page.

After perusing this Discourse, I couldn’t find a solid way to do full blown “code splitting” (whereby I break down my bundle into constituent parts/pages).

A simpler approach might be to only enqueue that particular JS file (written in ES6, using lots of import statements) when that specific page loads. I’m unsure how to do that, though…

Any ideas?

1 Like

I think you could create a new entry in resources/assets/config.json to build a page-specific bundle and set up a page-specific enqueue the normal WordPress way.

It’s not quite the same thing, but I wrote about how to do this with stylesheets here:

Essentially you’ll add the entry like this:

theme-name/resources/assets/config.json

{
  "entry": {
    "main": [
      "./scripts/main.js",
      "./styles/main.scss"
    ],
    "heavypage": [
      "./scripts/heavypage.js"
    ],
    "customizer": [
      "./scripts/customizer.js"
    ]
  },
  "publicPath": "/app/themes/theme-name",
  "devUrl": "http://mysite.dev",
  "proxyUrl": "http://localhost:3000",
  "cacheBusting": "[name]_[hash:8]",
  "watch": [
    "app/**/*.php",
    "config/**/*.php",
    "resources/controllers/**/*.php",
    "resources/views/**/*.php"
  ]
}

And then conditionally enqueue the bundle:
theme-name/app/setup.php

/**
 * Theme assets
 */
add_action('wp_enqueue_scripts', function () {
  if($condition) {
    wp_enqueue_script('sage/heavypage.js', asset_path('scripts/heavypage.js'), ['jquery'], null, true);
  }
}, 100);

This is all untested, written on an iPad but this is the gist of what will work at least.

Does that help?

7 Likes

Thank you, this is super helpful.

My only question is whether sage/heavypage.js will be processed by Webpack in this scenario?

Yes. That’s what this is. This is setting it up with webpack.