问题描述
我目前正在研究一个自耕农生成器,它必须复制一堆处理过的 ejs 文件来为新的子项目设置配置。为了避免单独列出每个文件,我只想获取整个目录并带上每个文件,删除 ejs 扩展名并使用相同的上下文应用模板。
在搜索文档时,我最终查看了 mem-fs-editor 的测试,发现 fs.copyTpl
在使用 glob 模式 https://github.com/SBoudrias/mem-fs-editor/blob/master/tests/copy-tpl.js#L85 时应该删除 ejs 扩展。
然而,即使尝试在孤立条件下(但在自耕农内)复制测试,扩展仍然存在:
1 'use strict';
2 const Generator = require('yeoman-generator');
3 const chalk = require('chalk');
4 const yosay = require('yosay');
5
6 module.exports = class extends Generator {
7 prompting() {
8 // Have Yeoman greet the user.
9 this.log(
10 yosay(`Welcome to the tiptop ${chalk.red('generator-ejs-glob')} generator!`)
11 );
12
13 const prompts = [
14 {
15 type: 'confirm',16 name: 'someAnswer',17 message: 'Would you like to enable this option?',18 default: true
19 }
20 ];
21
22 return this.prompt(prompts).then(props => {
23 // To access props later use this.props.someAnswer;
24 this.props = props;
25 });
26 }
27
28 writing() {
29 this.fs.copyTpl(
30 this.templatePath('ejs/'),31 this.destinationPath('out/'),32 )
33 }
34
35 };
其中 ejs
包含 file1.txt.ejs
和 file2.txt.ejs
。
输出是
> yo ejs-glob
_-----_ ╭──────────────────────────╮
| | │ Welcome to the tiptop │
|--(o)--| │ generator-ejs-glob │
`---------´ │ generator! │
( _´U`_ ) ╰──────────────────────────╯
/___A___\ /
| ~ |
__'.___.'__
´ ` |° ´ Y `
? Would you like to enable this option? Yes
create out/file1.txt.ejs
create out/file2.txt.ejs
我尝试将路径更改为 ejs/**.*
,但没有结果。当我自己尝试添加一个 options.processDestinationPath
函数时,它甚至没有被调用。
我是否还需要做其他事情才能完成这项工作?
解决方法
您可以使用 gulp-rename
,但我建议使用 1.2.2 版本,新版本可能会有一些 issue,至少我在当前 (2.0.0) 上有问题.
您需要调用 this.registerTransformStream
,请参阅:
我以稍微不同的方式使用它,调用我的模板 something.optional-ext.ejs
,然后删除 .ejs
。
writing() {
this.registerTransformStream(rename((renamePath) => {
// remove .ejs extension ans set the real extension if present
if (renamePath.extname === '.ejs') {
const lastIndexOfDot = renamePath.basename.lastIndexOf('.');
if (lastIndexOfDot >= 0) {
renamePath.extname = renamePath.basename.substr(lastIndexOfDot);
renamePath.basename = renamePath.basename.substr(0,lastIndexOfDot);
} else {
renamePath.extname = '';
}
}
// fix template prefix
if (renamePath.basename[0] === '_') {
renamePath.basename = renamePath.basename.slice(1);
} else {
renamePath.basename = '.' + renamePath.basename;
}
}));
this.fs.copyTpl(
this.templatePath(),this.destinationPath(),{
appName: this.props.appName
});
// note: write are also affected
this.fs.write('_props.json',JSON.stringify(this.props));
}