Search code examples
javascriptnpmwatchify

Compiling multiple script bundles using NPM and Watchify


I have a project where I'd like to compile separate script bundles - one main one that gets included on every page and a bunch of separate bundles that will get included only on specific pages.

I have a NPM script that looks like this:

"build-site": "watchify Scripts/site.js -o Scripts/bundle.js -v -d .",
"build-student": "watchify Scripts/modules/student.js -o Scripts/student_bundle.js -v -d .",
"start": "npm run build-site | npm run build-student",

So I run npm start and Watchify kicks in and starts watching the files. This part works well enough.

Whenever I make a change to the student module, both files get recompiled (no problem) but when I go to view the page in the browser I get an error that the module 'site.js' could not be found.

If I then go to the site.js file and modify something, the recompile occurs but this time it works well in the browser.

So the crux of it is that when I try to compile one file, I have to make a change to the other to get that to compile properly as well. I feel like the way I'm doing it is kind of unstable but I can't find much information on bundling multiple files with Watchify.

To summarise my question: How can I compile multiple bundles with Watchify in a way that avoids the above problem?


Solution

  • The problem seems to have been a pretty simple one in the end. One of the files I was trying to compile was actually being included in the other file.

    I suspect what was happening was site.js was being compiled and locked by npm, then compiling of student.js was starting up before site.js was ready.

    I fixed this by removing the redundancy and not compiling site.js by itself. It now gets included by student.js and I simply include student_bundle.js on the page instead of both site.js AND student_bundle.js.