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

前端 未结 4 530
误落风尘
误落风尘 2021-01-19 14:43

I hope you are well.

I\'m suddenly unable to render any external javascript in jade templates! To get to the bottom of things, I stripped it down to the bare minimum

相关标签:
4条回答
  • 2021-01-19 14:50

    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.

    0 讨论(0)
  • 2021-01-19 14:53

    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.

    0 讨论(0)
  • 2021-01-19 15:01

    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.

    0 讨论(0)
  • 2021-01-19 15:02

    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)
    
    0 讨论(0)
提交回复
热议问题