3

I'm trying to get my Pug template to render a script using Express. My file structure is as follows:

views
    public
        index.jade
        main.js

index.js

I have tried passing the name of the script as an argument to res.render('public/index', { bundle: '/main.js' }) with no luck.

Contents of my index.js:

const app = express();

app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'views/public')));

app.use('*', (req, res, next) => {
    res.render('public/index', { bundle: '/main.js' });
});

Contents of my index.jade:

doctype html
html
    head
        title SSR React
    body
        div#root
        script(src='#{bundle}')

I'm getting a strange error in the console. The name of the script is coming through, but I'm getting the error

Uncaught SyntaxError: Unexpected token <

The contents of main.js when I look at the console are as follows:

<!DOCTYPE html><html><head><title>SSR React</title></head><body><div id="root"></div><script src="/main.js"></script></body></html>

so, just the minified HTML which is being transpiled from Pug.

Can anyone shed some light here? Am I configuring Express incorrectly? Thanks.

SuperStar518
  • 2,814
  • 2
  • 20
  • 35
brownac
  • 61
  • 2
  • 7

3 Answers3

3

While writing inline JavaScript in Jade template you need to add a dot after the script tag. Also you should indent your code.

For example include external js like:

script(type='text/javascript', src='/socket.io/socket.io.js')

Inline js like:

script(type='text/javascript').
Shivani Sonagara
  • 1,299
  • 9
  • 21
1

I don't know Jade, but your Express setup is fine. You can see from the rendered HTML that Express is passing the correct value into your template, i.e. '/main.js'. You also know the bundle file is being served since you see it in devtools under 'sources'. The error you're seeing is almost definitely a problem with your transpiled/bundled React code. See ReactJS: unexpected token '<' for some steps you might try.

Ross Hunter
  • 131
  • 4
0

easy!

include TOP.pug
head
  script(type='text/javascript').
    function ExampData() {
    var ws = new WebSocket("ws://"blah.com:6789");
    ws.onopen = function() { ws.send("hola); };
    ws.onmessage = function(e) {
    // code comments like this are OK.
    el.innerHTML = e.data + "<br>" + el.innerHTML;
    };
    ws.onclose = function() { console.log("ws closed ..."); };
    }
| Example:
br
pre#logtag
br
| (Recent items are at the top)

script(type='text/javascript').
  var el = document.getElementById("logtag");
  ExampData()
Fattie
  • 27,874
  • 70
  • 431
  • 719