【问题标题】:How to reference a nunjucks template included in a node module?如何引用节点模块中包含的 nunjucks 模板?
【发布时间】:2020-07-09 17:54:01
【问题描述】:

如果我想用node模块打包一个nunjucks模板文件,如何引用打包好的模板文件,以便在全局安装包时通用?

我有以下节点文件,index.js:

#!/usr/bin/env node

var nunjucks = require('nunjucks');

var env = nunjucks.configure('./');
var template = env.getTemplate('template.html');
var output = template.render({
  h1_copy: "Foo and Bar"
});

console.log(output);

这里是template.html:

<html>
  <body>
    <h1>{{ h1_copy }}</h1>
  </body>
</html>

我将它设置为在 package.json 中有一个二进制命令:

"bin": {
  "make_output": "./index.js"
}

现在,如果我在全局安装它,我可以运行 make_output 来生成输出:

node-nunjucks$ npm install -g .
/usr/local/bin/make_output -> /usr/local/lib/node_modules/node-nunjucks/index.js
+ node-nunjucks@1.0.0
added 1 package in 0.099s

node-nunjucks$ make_output
<html>
  <body>
    <h1>Foo and Bar</h1>
  </body>
</html>

但这只有在我运行命令的目录中存在template.html 时才有效。如果我尝试从其他任何地方运行全局命令,它就找不到模板:

node-nunjucks$ cd ..
tmp$ make_output
/private/tmp/node-nunjucks/node_modules/nunjucks/src/environment.js:296
          throw err;
          ^

Error: template not found: template.html

如何引用 index.js 中的打包模板文件,使其使用包中的模板(/usr/local/lib/node_modules/node-nunjucks/template.html 中的模板),而不是在我的工作目录中查找模板?

【问题讨论】:

    标签: node.js npm nunjucks


    【解决方案1】:

    configure 调用是您要调整的调用。它告诉 getTemplate 在哪里寻找模板。它可以采用一组值,这些值引用了可以找到模板的多个目录。

    例子:

    #!/usr/bin/env node
    var nunjucks = require('nunjucks');
    
    var env = nunjucks.configure(['./', './node_modules/node_nunjucks/']);
    var template = env.getTemplate('inner.html');
    var output = template.render({
      h1_copy: "Foo and Bar"
    });
    var template2 = env.getTemplate('outer.html');
    var output2 = template2.render({
      h1_copy: "Foo2 and Bar2"
    });
    
    
    console.log(output);
    console.log(output2);
    

    在本例中,inner.html 位于 index.js 旁边的根目录中,outer.html 位于 node_modules/node_nunjucks 中。它只是 node_modules 文件夹的相对路径,但你可以更聪明地使用别名等等,这取决于你使用什么工具来构建。

    希望对您有所帮助。

    【讨论】:

    • 如果我为全局 node_modules 目录设置一个操作系统环境变量(例如 $NODE_LIB),并在配置调用中使用process.env.NODE_LIB,这可以工作。谢谢!
    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2020-08-16
    • 2018-10-14
    • 2021-12-31
    • 2021-04-16
    • 1970-01-01
    相关资源
    最近更新 更多