Gulp函数创建包含内容的文件

ee7vknir  于 2022-12-08  发布在  Gulp
关注(0)|答案(1)|浏览(187)

I'm pretty new to gulp and trying to figure out if it's possible to write a gulp function that creates a file for me, with some content, and places the files in a location. But I'm trying to create files with the same name of other files.
Here's my current setup:

dist
src
---modules
------item1.njk
------item2.njk
---new files

For each file in the modules folder I want to create an .njk file with the same name but different file contents. File contents are currently HTML but I want to write new code in the newly created files.

Intended output:

src/modules/item1.njk has contents:

<p>Hello World!</p>

src/modules/item2.njk has contents:

<p>Hello again, World!</p>

I want these file names to be used when creating these files with new contents:
src/new files/item1.njk has contents:

<link rel="stylesheet" href="../../css/styles.css">
{% block content %}
{% include "modules/item1.njk" %}
{% endblock %}

src/new files/item2.njk has contents:

<link rel="stylesheet" href="../../css/styles.css">
{% block content %}
{% include "modules/item2.njk" %}
{% endblock %}

How can I accomplish this?

ax6ht2ek

ax6ht2ek1#

我能够使用这个答案中的Map流建议,它允许我在将文件推到新文件夹位置之前编辑文件内容:
https://stackoverflow.com/a/38376568/5900050
我的最终脚本不需要原始文件内容,我想替换它,让我在这里:

.pipe(map(function(file, cb) {
  var fileName = file.basename.toString();
  // --- do any string manipulation here ---
  fileContents = '<link rel="stylesheet" href="../../css/styles.css">\n{% block content %}\n{% include "modules/body/'+fileName+'" %}\n{% endblock %}';
  // ---------------------------------------
  file.contents = new Buffer.from(fileContents);
  cb(null, file);
}))

相关问题