2

I am using express on a nodejs platform and serve my javascript library files using this directive

app.use('/static', express.static(__dirname + '/static'))

Now I want to be able to write something like that, inside one of these static files

[..] var host = <%= host %> [..]

Is there any possibility to expand variables inside statically served files?

4

3 回答 3

1

这是您可能想要改进的想法:

var ejs = require('ejs');

//Express.js setup
...

app.use('/public/js/myfile.js', function(req, res){
    var f = ejs.compile('var host = <%= hostname %>;');
    var fileContent = f({hostname: 'somevalue'});
    res.setHeader('Content-Type', 'application/javascript');
    res.setHeader('Content-Length', fileContent.length);
    res.send(fileContent);
});
app.use(express.static(path.join(__dirname, 'public')));

//Routes definition
...

我使用了 ejs,因为那是您已经使用的。所以想法是有一个中间件来捕获对那些“动态”javascript文件的请求,并使用模板引擎来编译内容。

请注意,我在这里使用了一个简单的字符串变量,但您可以从磁盘读取文件然后编译它。

干杯

于 2013-11-03T18:13:38.610 回答
0

请在此处查看我的答案:https ://stackoverflow.com/a/19812753/2728686

使用Jade模板引擎,您可以提供静态文件并将服务器端 javascript 变量发送到静态 HTML 文件(或任何翡翠模板),如下所示:

服务器端(server.js):

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.get('/', ensureAuthenticated, function(request, response){
    response.render('index', { data: {currentUser: request.user.id} });
});

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

意见/index.jade:

!!! 5
script(type='text/javascript')
    var local_data =!{JSON.stringify(data)}

include ../www/index.html
于 2013-11-06T13:11:36.160 回答
0

您可以使用lodashinexpress将loDash 的模板与 express 结合使用。

于 2013-11-02T10:12:08.667 回答