通过命令行创建多个相关样板文件的方法

Way to create mutiple, related boilerplate files via the commandline

不久前我问了一些可以让我创建样板的东西,并被指向 mush,但现在我正在寻找一些更高级的东西,可以让我转换变量,使用变量在文件名中,并允许我将文件目录定义为单个模板。

我的目标是能够 运行 类似 cat ./react_component.ms | name=MyComponent mush 的内容并生成如下所示的目录:

my_component/
  index.js
  my_component.jsx
  my_component.css
  my_component.spec
  my_component.md

每个文件都会有基于输入变量的样板文件:

import React, { Component } from 'react';

export default MyComponent extends Component {
  render() {
    return <h1>Hello There</h1>;
  }
}

最近在四处闲逛时,我得到了 sagui and yeoman 的指点,但这两个项目看起来都很繁重,旨在为整个项目创建样板,而不仅仅是为单个组件。

这是我想象中的事情类型:

templates/
  react-component.vars   <--- would define `snake_name` based on `name`
  react-component.ms/
    {{snake_name}}/
      index.js.ms
      {{snake_name}}.jsx.ms
      {{snake_name}}.css.ms
      {{snake_name}}.spec.ms
      {{snake_name}}.md.ms

下面会在里面 {{snake_name}}.jsx.ms

import React, { Component } from 'react';

export default {{name}} extends Component {
  render() {
    return <h1>Hello There</h1>;
  }
}

在我继续制作类似 this/try 的东西以添加到 mush 之前,有人知道是否有另一个模板库已经这样做了吗?

make 似乎是你想要的。这对新用户来说有点神秘,但你可以这样做:

# This is a Makefile

default:
    mkdir -p $(name)
    make $(files)

files := $(patsubst $(name)/my_component.%, $(name)/$(name).%, $(patsubst templates/%,$(name)/%,$(wildcard templates/*)))

$(name)/%: templates/%
    sed -e 's/my_component/$(name)/g' $< > $@

$(name)/$(name).%: templates/my_component.%
    sed -e 's/my_component/$(name)/g' $< > $@

将允许 make name=fred:

$ make name=fred
mkdir -p fred
make fred/index.js  fred/fred.jsx
sed -e 's/my_component/fred/g' templates/index.js > fred/index.js
sed -e 's/my_component/fred/g' templates/my_component.jsx > fred/fred.jsx

给定上面的 Makefile 和上面输出中建议的模板目录。

我最终制作了一个名为 Genierator 的 npm 包。