Separating out custom javascript in Sage

Hi,

It is unclear to me what the best way is to load specific javascript files for specific pages in Sage.

I am able to add custom javascript by requiring it in the manifest.json using this pattern:

    "main.js": {
          "files": [
            "scripts/main.js", 
            "scripts/app.js"
          ],
          "main": true
        },

But say I wanted to require a file called scripts/filters.js only on the About page. What is the best way to require certain modules in this way using Sage conventions?

You could do something like this:

{
  "dependencies": {
    "about.js": {
      "files": [
        "assets/scripts/filters.js",
        "bower_components/lib-for-about-only/dist/lib-for-about-only.js"
      ]
    },
    "main.js": {
      "files": [
        "scripts/main.js"
      ],
      "main": true
    },
    "main.css": {
      "files": [
        "styles/main.scss"
      ],
      "main": true
    },
    "customizer.js": {
      "files": [
        "scripts/customizer.js"
      ]
    },
    "jquery.js": {
      "bower": ["jquery"]
    }
  },
  "config": {
    "devUrl": "http://example.dev"
  }
}

Couple things to note: the source dir of the new file is the theme root and not assets/ like the existing manifest, so you’ll need to account for that in your source paths. Also, libraries you install via Bower must be included manually (otherwise they won’t be built into your main.js).

Helpful debugging tip: Sage: Wiredep & SASS Framework

1 Like

Ok great, so now my globs look like this:

But I am not getting the code from my about.js script loading in my minified main.js.

I am assuming I wouldn’t enque this script separately? And once I do that, how do I map that about.js file to the body class=“about” page ?

You would enqueue about.js separately and conditionally, it will not be included in main.js.

If you want the script itself to fire only on certain pages then please be sure to read the comments on DOM based routing and use main.js as a template for your new file.

Cool, so if I go the second route–to avoid main.js from becoming unwieldy with js code-- what is the best way to “require” other views/javascript files ?

Much appreciated,

You would enqueue about.js separately and conditionally

Not sure what’s unclear