How to generate a pure JavaScript file with Jade
Asked Answered
S

2

5

I know that Jade is for producing HTML instead of JavaScript, but for a project I'm working, it would be great, and a huge time saver, if I could do this without adding a pipe in every line:

|   (function(){
|       //Some JavaScript Code
|       var foo="#{bar}";
|       console.log("This a JavaScript file generated with Jade");
|   })()

The idea is to use the output of this template as the source of a regular JavaScript include like this:

<script type="application/javascript" src="foo.generated.js"></script>

So doing something like this:

script(type="application/javascript").
    (function(){
        //Some JavaScript Code
        var foo="#{bar}";
        console.log("This a JavaScript file generated with Jade");
    })()

won't solve my issue, because I need to output pure JavaScript with no DOM container element.

Is there another way to do this without adding pipes to every line? Or I have to assume that Jade was designed to produce only HTML, give up, and find other solution without Jade?

Thanks in advance!

Saucer answered 25/9, 2013 at 15:3 Comment(5)
You’re generating a JavaScript file with Jade? Why?Cachalot
@minitech I know Jade is not the ideal tool for doing that, but I'm asking because the project I'm working on, has a feature that allows me to generate HTML modules from an internal model, and for a particular functionality that I have to develop, I would save a lot of time and lines of code if I could use the same already developed feature to generate a pure javascript file. Thanks!Lavernalaverne
So your JavaScript contains embedded HTML?Cachalot
@minitech not necessarily, but it gives me access to information provided by other internal services, which is injected into the model passed to the template when rendering. Usually this is used to generate HTML, but in this particular case, I need to produce a JavaScript file dynamically for every user, with long chaching times.Lavernalaverne
What kind of data goes into the template? Is it just string replacement, or is it more complex? (The answer to your question, by the way, is “yes”. For example, Jade is going to escape a lot of things that you’d probably rather not have escaped, and it’s going to not escape some things, too.)Cachalot
H
0

Produce all XML, include HTML. And jade was not designed to cast large blocks of javascript. The best thing you can do is create a method for obtaining these large blocks, and modifying variables. As it is doing in Example.

Havildar answered 22/10, 2015 at 0:0 Comment(0)
E
0

I think you should use:

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
res.end(`(function(){
    //Some JavaScript Code
    var foo="${bar}";
    console.log("This a JavaScript file generated with Jade");
})()`);
Empathy answered 31/12, 2018 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.