Friday, August 19, 2016

Combining multiple #javascript files into one in #PyCharm using File Watcher + #Python script

I'm working on a website and currently have one large javascript file with several classes in it, which makes the code overall less readable / harder to maintain. But I also want to only include one script file in the HTML doc, and also only make the browser download one script instead of several.

Note: I am using PyCharm

There are plenty of third party tools that you can use to do this. However, I attempted to use one, and it didn't work. So instead of wasting more time, I decided to keep it simple and write my own tool that does it.

Here's the steps I did:
1. Split the big JS file into several small ones and put them in a subdirectory

2. Delete the big JS file

3. Add a Python file called This simply takes the list of files, reads them, and then outputs them into another file
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)

files = ["smallfile1.js", "smallfile2.js", "smallfile3.js"]

outputFile = "";

for file in files:
    with open(file, 'r') as f:
        outputFile += " " +

with open("../bigfile.js", 'w+') as output:

4. Configure the File Watcher in PyCharm so that it calls this script whenever I save one of the subfiles

  • File > Settings > File Watcher
  • Add new
  • Scope = point to the subdirectory containing the small JS files and click Include Recursively
  • Program = C:\Python27\python.exe
  • Arguments = <path to>
5. Save it all

6. Try editing one of the small JS files and then saving it. should run and you should now see the combined big JS file sitting in the correct spot.

Note: This does not minimize the JS file. Remember that optimizations are a waste of time until you can prove that you have a performance problem to solve. In my case, applying a minimizer to bigfile.js barely saves any space, so I'm not going to waste my time attempting to automate the minimization process UNTIL a performance problem arises where the time spent solving the problems has quantifiable benefits.

No comments:

Post a Comment

There was an error in this gadget