如何引用节点模块中包含的 nunjucks 模板?

How to reference a nunjucks template included in a node module?

如果我想打包一个带有节点模块的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 中的模板)而不是在我的工作目录中查找模板?

配置调用是您要调整的调用。它告诉 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 文件夹的相对路径,但您可以更巧妙地使用别名和诸如此类的东西,具体取决于您使用的构建工具。

希望对您有所帮助。