We have finally reached the end of the line (maybe 😋).
Building upon the shoulders of our past code
We have already invested a lot of time and afford into streamlining our code bundle.
In this final puzzle piece we will look at all our services and see if we find any methods and members that we only use privately.
Gather all the used services methods
This is pretty similar to searching for used methods in templates from the last article. Instead of looking at hmlt files we will search in all of our js files.
Also the regex (at least in my case) changed a bit.
I now search for all strings that start with a big letter followed with at least one small letter. The whole thing needs to be prefixed with " " (inside none class syntax files), "_" (normal class service injection), or "!" (negated none class syntax).
const matches = string.match(/[ |_|!][A-Z]+[a-z]+[a-zA-Z]*\.[a-zA-Z0-9_-]+/gm);
Replacing that and adapting it to use a different Set as before, we end up with:
const stringsFromJs = new Set();
const tGatherFromJs = () => {
return gulp.src(packagePath + '/**/*.js', {base: './'})
.pipe(through.obj((file, _, cb) => {
const string = file.contents.toString();
const matches = string.match(/[ |_|!][A-Z]+[a-z]+[a-zA-Z]*\.[a-zA-Z0-9_-]+/gm);
if (matches) matches.forEach((match) => stringsFromJs.add(match.substring(1)));
cb();
}));
};
Oh wait, we can reuse or existing function
As we already loop over all our js files (tFindUnusedPublic) we can just add our service check.
const tFindUnusedPublic = () => {
const stringToSearchT = [...stringsFromTemplate].join(' ');
const stringToSearchJs = [...stringsFromJs].join(' ');
// get public from js files
return gulp
.src(packagePath + '/**/*.js', {base: './'})
.pipe(through.obj((file, _, cb) => {
// ... some stuff we already do
// components and directices
let baseName = string.match(/controllerAs: '(.*)'/);
if (baseName) { /*...*/ }
// services
let serviceName = string.match(/\.service\('(.*)'/);
if (serviceName) {
serviceName = serviceName[1];
const uniquePublic = getPublic(string);
string = searchInString(uniquePublic, serviceName, stringToSearchJs, string, false);
}
// ... more some stuff we already do
}))
.pipe(gulp.dest('./'));
};
So with this little addition we now also check our services for unused methods and members.
Ideally our compiled code base should be smaller now (I saved about 100kB) and our users should be a bit more happy.
I hope that you where also able to squeeze a little more performance out of your angularjs project.
All the best and enjoy frontending 😉
Top comments (0)