问题
How do I require
a library so that it works inside Jade.
Like if I want to be able to use CircularJSON in Jade
script var object = #{CircularJSON.stringify(object)}
I would basically need to define the function from that library into Jade
- var CircularJSON = function(e,t){function l(e,t,o){var u=[],...//whole function
which would be impractical and possibly impossible for much more complex libraries.
Is there a way to somehow simply require
it instead?
回答1:
var myLib = require('../mylib');
response.render("index.jade", {
lib : myLib
});
index.jade
now has the myLib object. Now just use as you would anywhere else.
回答2:
Just require it in node and pass it to the template in the locals
. locals
can include functions as well entire modules, objects and scalar data.
回答3:
I like to take an approach similar to Peter Lyons and Zhifeng Hu (in another post), but instead of requiring everything into locals, I just require "require", then I can pull things in as needed in my templates.
app.use((req, res, next) => { res.locals.require = require; next() })
and then in Jade/Pug
- const moment = require('moment')
div Created at: #{moment(data.createdAt).fromNow()}
Basically the same thing, but I can keep the require code in the template where it's used.
来源:https://stackoverflow.com/questions/24007559/require-a-javascript-library-inside-jade