【问题标题】:node.js/Jade - How to pre-compile jade files and cache it?node.js/Jade - 如何预编译jade文件并缓存它?
【发布时间】:2015-08-21 18:01:02
【问题描述】:

框架:node.js / express.js / Jade

问题:在生产环境中,当一个jade文件通过express渲染时,jade缓存是它所以未来的渲染速度更快。

当我启动 node.js 应用程序时,如何预编译(或)预渲染(如预热)所有的翡翠文件,以便在请求开始时它已经在缓存中......

我可以使用文件夹递归,我只需要知道如何预编译(或)预渲染。

这可能吗?

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

    Jade 内置了模板预编译和缓存。

    http://jade-lang.com/api/

    只需将cache: true 选项指定为jade.compileFile,然后遍历所有模板文件。

    var options = {cache: true};
    
    // iterate/recurse over your jade template files and compile them
    jade.compileFile('./templates/foo.jade', options);
    
    
    // Jade will load the compiled templates from cache (the file path is the key)
    jade.renderFile('./templates/foo.jade');
    

    【讨论】:

    • 无论您喜欢哪里...您都可以直接从 Express 路由中调用 jade.renderFile,但我怀疑如果您在 express 中使用 Jade 作为视图引擎,它将利用内置缓存。
    【解决方案2】:

    如果你不使用任何参数,你可以使用 grunt 或 gulp 直接将 Jade 模板编译成 HTML 并让它监视文件修改

    从命令行尝试: jade view/map-beacons.jade -D

    如果您确实需要使用参数,我会使用类似 Andrew Lavers 的答案。

    compileFile 返回一个可用于传入参数的函数,即fn({ myJsVar: 'someValue' })

    命令行中还有一个客户端选项,但我没有发现它有任何用处: jade view/map-beacons.jade -cD

    【讨论】:

      【解决方案3】:

      我做这个解决方案,这段代码在 http.createServer 函数之外

      let cache_index=jade.renderFile('index.jade');
      

      当返回视图时

      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/html');    
      res.end(cache_index);
      

      当使用这个解决方案服务器时,返回索引为 1ms 但没有解决方案服务器返回索引在 150 毫秒到 400 毫秒之间

      结果:

      带有缓存的图片 1

      没有缓存的图2

      【讨论】:

        猜你喜欢
        • 2013-07-21
        • 2013-05-05
        • 2016-08-31
        • 2023-04-09
        • 2013-12-18
        • 2013-04-17
        • 2014-11-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多