[英]Loading ES6 template string from file
Let me explain my actual problem. 让我解释一下我的实际问题。 I have a template string which could look like this:
我有一个模板字符串,看起来像这样:
/${name}
get
post
/{id}
get
/file-content
get
post
The indentation has to remain untouched. 缩进必须保持不变。
Now if I were to use such a template string it might look like this: 现在,如果我要使用这样的模板字符串,它可能如下所示:
function test(arr) {
let ret = []
arr.forEach(
function(name) {
return `/${name}
get
post
/{id}
get
/file-content
get
post`
return ret
}
)
}
Looks pretty ridiculous, right? 看起来很可笑,对吧? I could of course put extra spaces into my template to match my code indentation, but then I'd have to perform unnecessary operations on the string afterwards to normalize it again.
我当然可以在我的模板中添加额外的空格以匹配我的代码缩进,但之后我必须对字符串执行不必要的操作以再次标准化它。
So my idea was to move the template string to an external file and require
that file whenever I need the template string. 所以我的想法是将模板字符串移动到外部文件,并在需要模板字符串时
require
该文件。
But require can't be used for that problem because it's nothing more than a text file and I certainly don't want to read that file from disk every time I need it and perform an eval
on it. 但是require不能用于那个问题,因为它只不过是一个文本文件,我当然不希望每次需要它时从磁盘读取该文件并对其执行
eval
。
I could think of several workarounds for this problem, but I just cannot seem find a satisfying solution. 我可以想到这个问题的几种解决方法,但我似乎无法找到令人满意的解决方案。
How about this: 这个怎么样:
// template.js
module.exports = name => `
/${name}
get
post
/{id}
get
/file-content
get
post
`.trim()
// app.js
const template = require('./template')('name');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.