【发布时间】: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 中的模板),而不是在我的工作目录中查找模板?
【问题讨论】: