Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to minify JS code inside ejs files?

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.

like image 853
Vadorequest Avatar asked Nov 08 '14 17:11

Vadorequest


2 Answers

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))
  })
})
like image 53
drj Avatar answered Sep 21 '22 16:09

drj


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>
like image 21
Doron Segal Avatar answered Sep 19 '22 16:09

Doron Segal