Axel Stone
Axel Stone

Reputation: 1580

How to minify my personal jquery frontend microframework

I've made my personal jQuery microframework with useful utilities. It has a directory structure like this:

/jspocket
  - jspocket.js
  /scripts
    - include.js
    - navigation.js
    - slider.js
    - popups.js
    ...

Therefore it is imported into html like this:

<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/jspocket/jspocket.js"></script>

In jspocket.js is this code for importing all the .js files from '/script' directory into an html file:

$.getScript(jspocket_dir + "/scripts/navigation.js");
$.getScript(jspocket_dir + "/scripts/popups.js");
$.getScript(jspocket_dir + "/scripts/slider.js");
$.getScript(jspocket_dir + "/scripts/include.js");
...

Now I would like to create a minified version of my framework so there will be only one file jspocket.min.js. But the problem is that the commands like:

$.getScript(jspocket_dir + "/scripts/navigation.js");

will not work, simply becouse scripts/navigation.js does not exist in minified version, it should be all in one file.

So the question is how could I minify the framework into one file (without manually copying all the code into one file)? Should I change the way scripts are imported? Does the new import/export features of JS solve it somehow? How is this problem solved in general? I'm using node.js and npm, so maybe there could be a good packages for this?

Upvotes: 1

Views: 38

Answers (1)

Hyyan Abo Fakher
Hyyan Abo Fakher

Reputation: 3527

You need to use a build system to minify the files into one file but leave jspocket.js out of the process.

There are many build systems out there like GruntJs , Webpack or Gulp

This following is how to do it in Gulp

// the plugins
var gulp = require('gulp')
var uglify = require("gulp-uglify");
var concat = require('gulp-concat');

// task
gulp.task('minify-js', function () {
    gulp.src([
       ./jspocket/scripts/navigation.js,
       // the rest of your files in your order
    ]) 
    .pipe(concat('jspocket.min.js'))  
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

then run gulp minify-js

Upvotes: 1

Related Questions