express-uglify-assets
A middeware for express that concatenates and bundles your js and css files on the fly.
assets.addJs('javascripts/library.js');
assets.addJs('javascripts/main.js');
assets.renderJs();
<script src="/javascripts/library.js"></script>
<script src="/javascripts/main.js"></script>
<script src="/04e9f94bbeb85c9f9ecb98d724cd2cc0.js"></script>
Install
npm install express-uglify-assets --save
Usage
Adding the middleware to your express app
expressUglifyAssets([options])
var express = require('express');
var expressUglifyAssets = require('express-uglify-assets');
app.use(expressUglifyAssets({
process: true,
root: __dirname + '/public',
rebaseTo: 'http://localhost:3000/'
cleanCssOptions: {
wrapAt: 100
},
uglifyJsOptions: {
output: {
max_line_len: 100
}
},
header: {
{'Cache-Control': 'public, max-age=31557600'}
}
}));
Adding js/css in your template and output them
The middleware adds the following functions to your template and to res.assets in your express route callback.
assets.addCss(file)
assets.renderCss([options], [namespace])
assets.addJs(file)
assets.renderJs([options], [namespace])
example with the template engline ejs
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Example assets</title>
<% assets.addCss('stylesheets/style.css'); %>
<%- assets.renderCss(); %>
</head>
<body>
<h1>asset express ejs example</h1>
<p>
On this page the css and js is minified. Go <a href="/not-minified">here</a> to see the not minified version.
</p>
<% assets.addJs('javascripts/library.js'); %>
<% assets.addJs('javascripts/main.js'); %>
<%- assets.renderJs(); %>
</body>
</html>
Adding attributes to the output
assets.renderJs({attr: {async: true, id: 'my_awesome_script'}});
Namespaces
assets.addJs('javascripts/advert.js', 'advertise');
assets.addJs('javascripts/library.js');
assets.addJs('javascripts/main.js');
assets.renderJs();
assets.renderJs({attr: {async: true}}, 'advertise');
Performance
When {process: true} is set, each asset is generated in sync the first time assets.renderJs/assets.renderCss is called. So the first page load will be slower. The minified and combined css/js is cached in memory. Subsequent calls with the same options and files will be served from memory. This also means changing the content while the server is running will not change the content. You need to restart your app. The Files are served with the header Cache-Control: public, max-age=31557600'
When {process: false} is false, what is the default in development, the files are send with express.sendFile(), so changes will be available without restarting the app.
License
express-uglify-assets is licensed under the MIT license.