6

I'm wondering if it is possible to minify the JS code contained inside template files like EJS files.

Is it useful? I'm thinking about performances. It's still a way to hide comments, explanations.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
Vadorequest
  • 16,593
  • 24
  • 118
  • 215
  • Why wouldn't you be able to? – Scimonster Nov 08 '14 at 17:05
  • Because the file is rendered by the server itself, not downloaded by the browser as usual. I'm just wondering if it is useful, and if it is then how to do it. – Vadorequest Nov 08 '14 at 17:47
  • Put your scripts in external .JS files that are included via script tags. Then minimize your .JS files. – jfriend00 Nov 08 '14 at 17:56
  • But that's not what I want to do. – Vadorequest Nov 08 '14 at 18:05
  • Well, that's how you minimize JS. Otherwise, you'd have to find a JS minimizer that can handle non-script stuff in ejs files. I'm not aware of one. – jfriend00 Nov 08 '14 at 20:14
  • I know that's the traditionnal way to minify JS and I already do that, this is something else and I was wondering about the possibilities here. – Vadorequest Nov 09 '14 at 16:55
  • I know this is old, but it came up in a google search, and I'm interested in a solution like this. I can see why EJS minification would be useful. Minifying isn't really the issue, it's the EJS breakouts like <% %>, <%- %> and <%= %>. You want to preserve the server-side values while minifying the javascript. For an edge case, what if the server is rending javascript? How would that be handled and how would the minifyer know there's not a referenced dependency inside the rendered result? Think on this further, I will. – drj May 18 '18 at 23:49

2 Answers2

2

This seems to be the best solution. Basically, you want to use the EJS renderFile method, and then use UglifyJS to uglify the rendered result.

app.get('/js/my.js', (req, res) => {
  var data = {foo:'bar'}
  ejs.renderFile('views/js/my.js.ejs', {data}, (err, js) => {
    if(err) return res.status(500).send("error")
    res.setHeader('Content-Type', 'text/javascript')
    res.send(UglifyJS.minify(js))
  })
})
drj
  • 533
  • 2
  • 16
1

You can use node-minify for minifying your Javascript, HTML and CSS files.

Also, you shouldn't minify the files on render (on an incoming request). I usually use a my EJS files to pass configurations to the UI and load the UI from S3 or from the public end-point.

You can have index.ejs that includes a script tag

<script type='text/javascript'>
  var clientSideConfig =<%-JSON.stringify(backendConfigurations)%>
</script>
<script src="/public/your_minified_vuejs.js"></script>
Doron Segal
  • 2,242
  • 23
  • 22