Build a JavaScript Compressor tool using NodeJS, ExpressJS, Jade, UglifyJS tutorial Read more: http

You are here: Home / Javascript / Build a JavaScript Compressor tool using NodeJS, ExpressJS, Jade, UglifyJS tutorial

BUILD A JAVASCRIPT COMPRESSOR TOOL USING NODEJS, EXPRESSJS, JADE, UGLIFYJS TUTORIAL

by jaspreet chahal on january 17, 2013 leave a comment

X

Welcome MatePlease give this post a +1 if you like it Also If you find this post useful, you might want to subscribe to the RSS feed for updates on this topic. Cheers!

Document version number: initial post

As the title states its a beginners tutorial with a lot of stuff to learn.

This tutorial exist to give you a little bit of understanding on how things like NodeJS, ExpressJS, bootstrap, jQuery and Jade template engine work together.

Web Application

In this tutorial we will be creating a full web application with 2 pages.

  1. Main page where people can compress their Javascript files
  2. About Page which explains a bit about our app

The web application that we are gonna write address a problem about how to use UglifyJS to compress the JavaScript files. Advanced demo of the application we are going to write can be found here

http://icompressjs.com

I am going to add more feature to the above app but for this tutorial lets keep things simple.

I hope that you have installed NodeJS on your box. If you haven’t here are instructions to install it on Ubuntu 12 

If you are using Windows you can just download the installer and node will be available from command line.

After your installation npm and node commands will be available to your from command prompt. npm stands for Node Package Manager and it helps install Node Packages.

First up create a folder somewhere on your file system called uglify All our App files will go under this folder.

To start with lets create a package.json file under our parent folder (uglify) with the following contents in it

  1. {
  2. "name":"NodeJS-UglifyJS",
  3. "description": "A learning project for NodeJS and Express",
  4. "version": "0.0.1",
  5. "private": false,
  6. "dependencies": {
  7. "express": "3.0",
  8. "uglify-js":"1.3.4",
  9. "jade":"0.27.7"
  10. }
  11. }

Above package file is pretty easy to understand. Main part in above file is dependencies bit and we will see in a second how its really easy to install dependencies for you project in one hit

Now we will just run the following command

make sure that you you are in same directory as package.json and then run this command

  1. npm install

This will install node modules essential to run our code smoothly.

So node modules that will get installed are Express framework, uglifyJS, Jade template engine

Lets now create couple of more folders in your working directory called public and views and also create a file with name app.js

I’ll explain in a bit what app.js is all about. So here is a screenshot of our folder structure for the time being

Under public folder I have created three sub folders as shown below

As you can see how I’ve included twitter bootstrap (the CSS framework for responsiveness) under the css folder and then all my public images goes to img folder and likewise all my javascript goes in js folder

Now lets start to work on our app.js file

If you are unaware what expressJS is, then you must read some documentation on Express which can be found here

expressjs in broader terms is a node framework that makes you life easier a bit and save you many lines of code.

ok! lets carry on with our app.js file, app.js defines our application and carry most of the code that deals with user requests.

Here is basic code for our app.js file

  1. // instantiate express
  2. var express = require('express');
  3. var app = express();
  4. // handle request parsing, this enables request body parsing
  5. // API reference http://expressjs.com/api.html#bodyParser
  6. app.use(express.bodyParser());
  7. // enable compression
  8. app.use(express.compress());
  9. // enable router, router is responsible to route our requests to different actions
  10. app.use(app.router);
  11. // serve static files, I am directing express to use public folder as my assets folder to server images/js/css files
  12. app.use(express.static(__dirname + '/public'));
  13. // serve views, we will touch base on this in a bit
  14. app.set('views',__dirname+'/views');
  15. // template engine, tell express to use jade as our template engine for view handling
  16. app.engine('jade', require('jade').__express);
  17. // home page request redirected to compress action
  18. // does not have any advantage, just showing how to forward requests to different actions
  19. app.get('/', function(req, res){
  20. res.redirect("/compress");
  21. });
  22. // compress action, this is something that you will see as you home page
  23. app.get('/compress', function(req, res){
  24. res.render('index.jade', {path: req.path,ttl:"Javascript Compressor and beautifier built on Nodejs"});
  25. });
  26. app.listen(8080);

Please note that we are not using full MVC in our application, its just views that are separated out. depending on the complexity of your Node App you should be looking for a MVC structure that will help immensely with code maintainability. I won’t recommend that your app.js should go beyond few 10s of lines. We will add one more request handler in our app.js file in a bit

please note that app.listen() tells node which port your application is listening to. In our case its port 8080.

ok! before we can kick of our application we have to look at our view file. So here is a full structure of my views folder for icompressjs.com

We will be concentrating just on layout.jade, header.jade, footer.jade and index.jade in our example application

Remember! that in our app.js we told node to use jade as our template engine. Know more about jade by browsing official documentation page located here

https://github.com/visionmedia/jade#readme

We have a common layout page that will be applied to all other files as shown below

File layout.jade

  1. !!! 5
  2. html
  3. include header
  4. block content
  5. include footer

All whitespaces are important else your file may not work or produce unexpected results. I will not be explaining about jade how it works but let me share a couple of cool cssdeck’s that explain much of the working of jade

  1. Part 1
  2. Part 2

so as you can see that we are using HTML5 as our doctype with !!! 5 declaration

Please remember “block content” is a reference which will be replaced by actual index.jade contents during processing. Its explained later in this article. Just remember this reference for the time being.

then we are including our header file that have our navigation and other includes that will be common to all sub templates, lets check it out

  1. head
  2. title= ttl
  3. link(rel="stylesheet", href="/css/bootstrap.min.css")
  4. link(rel="stylesheet", href="/css/site.css")
  5. script(type="text/javascript",src="/js/jquery.js")
  6. script(type="text/javascript",src="/js/bootstrap.js")
  7. script(type="text/javascript",src="https://apis.google.com/js/plusone.js")
  8. //if lt IE 9
  9. script(src="http://html5shim.googlecode.com/svn/trunk/html5.js", language="text/javascript")
  10. body
  11. div.navbar.container
  12. img(src="/img/icompressjs.png",style="opacity:0.7;width:170px;height:60px")
  13. br
  14. div.navbar-inner
  15. a(class="brand",href="/") icompressjs
  16. ul.nav
  17. li(class="#{path==='/compress' ? 'active' : ''}"): a(href="/compress") compress
  18. li: a(href="http://jaspreetchahal.org") A service by jaspreetcChahal.org

Before we proceed with our index.jade template lets quickly check whats in our footer.jade file

  1. br
  2. footer.container copyright © <a href="JaspreetChahal.org" target="_blank">Jaspreet Chahal</a> Powered by <a href="http://nodejs.org" target="_blank">Node JS</a>, <a href="http://expressjs.com" target="_blank">Express JS</a>, <a href="http://twitter.github.com/bootstrap.org" target="_blank">Bootstrap</a>, <a href="http://jade-lang.com/" target="_blank">Jade</a> and <a href="http://jade-lang.com/" target="_blank">Uglify JS</a> {<a href="/source">Download iCompressJS Source</a>}

You can have whatever you like in your footer.

Lets now check out out index.jade view

  1. extends layout
  2. block content
  3. div.container
  4. h1 Paste your JavaScript code below to compress it
  5. form(method='post',onSubmit="return false",id="compress-form")
  6. div.row
  7. div.span2
  8. label
  9. input(type="checkbox",name="lift_vars",value="1",style="display:inline-block;float:left;margin-top:4px")
  10. |   Lift vars
  11. div.span2
  12. label
  13. input(type="checkbox",name="inline_scripts",style="display:inline-block;float:left;margin-top:4px")
  14. |   Escape &lt/script>
  15. br
  16. textarea(name="js",id="js",style="height:300px;width:98%")
  17. br
  18. // input(type='hidden', name="_csrf", value=token)
  19. input.btn.btn-success.btn-large(type="button",name="submit",value="Compress it",id="compress")
  20. h1 Compression result
  21. textarea(name="result",id="result",style="height:300px;width:98%")
  22. input.btn.btn-inverse.btn-large(type="button",value="Select All",onclick="$('#result').select()")
  23. script
  24. $(document).ready(function(){
  25. $("#js").focus();
  26. $("#compress").click(function(){
  27. $.ajax({
  28. type:'POST',
  29. data:$("#compress-form").serialize(),
  30. url:'/compressit',
  31. success:function(data) {
  32. $("#result").val(data);
  33. }
  34. });
  35. });
  36. });

Couple of things to note above

  1. extends layout is a reference to layout.jade and explicitly telling that in layout.jade look for
  2. block content and put the contents at its place

Other stuff is just normal HTML and a click event handler (jQuery) added at the end for compress it button

Alrighty! with all the files in place its time to run our app

run your app as

  1. node app.js

If there are any issues you will know straight away. the code above is verified so it should work without giving much grief.

Now that if some other process is not already using port 8080 its time to direct your browser to http://127.0.0.1:8080

You should see something like this

Read more: http://jaspreetchahal.org/build-a-javascript-compressor-tool-using-nodejs-expressjs-jade-uglifyjs-tutorial/#ixzz2Q9RaykuD

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏芋道源码1024

面试问烂的 Spring MVC 过程

来源:https://www.jianshu.com/p/e18fd44964eb

1933
来自专栏菩提树下的杨过

Silverlight Telerik控件学习:弹出窗口RadWindow

几乎所有的业务系统都有弹出窗口,典型场景有二种 : 1、简单的弹出一个对话框显示信息,比如下面这样: ? 这个很简单,代码示例如下: DialogParamet...

2125
来自专栏一个会写诗的程序员的博客

6.3 Spring Boot集成mongodb开发小结

本章我们通过SpringBoot集成mongodb,Java,Kotlin开发一个极简社区文章博客系统。

2063
来自专栏Lambda

编程规范

领域层–编码规范 2018年4月4日14:10:38 Controller层编写规范 controller层只是负责从service层获得数据,对外暴露API接...

3706
来自专栏Ryan Miao

MongoDB - basic

mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github....

3296
来自专栏向治洪

react native 调用原生UI组件

在React Native开发过程中,有时我们想要使用原生的一个UI组件或者是js比较难以实现的功能时,我们可以在react Naitve应用程序中封装和植入已...

69710
来自专栏Java3y

JsChart组件使用

JsChart是什么? JSChart能够在网页上生成图标,常用于统计信息,十分好用的一个JS组件。 使用JsChart 一。导入jscharts.js 二。编...

4179
来自专栏余林丰

SpringMVC——DispatcherServlet的IoC容器(Web应用的IoC容器的子容器)创建过程

在上一篇《Spring——Web应用中的IoC容器创建(WebApplicationContext根应用上下文的创建过程)》中说到了Web应用中的IoC容器创建...

2535
来自专栏蘑菇先生的技术笔记

多线程中的锁系统(四)-谈谈自旋锁

3007
来自专栏程序员的酒和故事

Go实战--实现简单的restful api

生命不止,继续 Go go go !!! 今天跟大家介绍一下如何使用go创建一套restful api,我们依托于开源库gorilla/mux。 let’s g...

3734

扫码关注云+社区

领取腾讯云代金券