static javascript not rendering in jade (with express/node.js)

无人久伴 提交于 2019-12-01 19:33:28

you need to pass your script from the controller like that:

app.get('/', function(req, res){
  res.render('index', { title: 'Express', scripts: ['javascripts/script.js']});
});

and then in your head in layout.jade:

- each s in scripts
    script(src=s)

Make sure your js files are exposed as static resources.

In layout.jade...

!!!5
html
   head
      script(src='js/helper.js')

In app.js...

app.use(express.static(__dirname + '/public'));

Once I put the 'js' folder under the 'public' folder, helper.js loaded without issue. Simple, but I'm new to this whole thing and I didn't get that at first.

Why do you have a beginning forward slash '/' in your Jade script tag? With your script in <root_dir>/public/javascripts/script.js, the correct way to reference it in Jade is script(src="javascripts/script.js"). At least that is what is working on my installation. The same is true for other assets like CSS or images in the /public directory.

Thanks to Rob (you can find his answer above), for pointing in right direction. I just want to add a little reference so it might seem more natural than any magic.

In the express documentation here, its mentioned that if static files like css, images etc are to be served then one need to declare it using

app.use(express.static("_dirName"));

I was facing same issue with using images in html code. With this, it works fine now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!