Keep code snippets directly in your project repository and let anyone create files easily and quickly.
First, install the package:
yarn add --dev project-snippets
# or npm
npm install --save-dev project-snippets
Now you have available snippet
command, let's use this in package.json
as create
script:
{
"scripts": {
"create": "snippet create"
}
}
You can run this by typing yarn run create
or npm run create
, but first you need .snippets
directory with your code templates.
For example you like to make a snippet for components in /src/components/*.js
, then .snippets
directory structure should look like this:
.snippets/
src/
components/
MySimpleComponent.snippet/ ← Snippet name, this dir will be omitted
(SomeName).js.tpl ← Snippet files or even directories
(someName).css.tpl ← .tpl extension is important!
Now after running the create
command, you will see list for your snippets. If you select MySimpleComponent
and then enter the name eg. circle button
it will create a file:
src/
components/
…
CircleButton.js
circleButton.css
…
Let's look inside the files.
Inside the files will we use ejs templates:
(SomeName).js.tpl
:
import '<%= someName %>.css'
export function <%= SomeName %>() {
// ...
}
And similarly for (someName).css.tpl
.
.<%= someName %> {
/* ... */
}
Finally, that's all, now you can run this command again and you will receive ready to use CircleButton.js
and circleButton.css
files:
import 'circleButton.css'
export function CircleButton() {
// ...
}
.circleButton {
/* ... */
}
--dry-run
- show the contents of files without creating them
The following variables are now available:
- Camel case:
someName
- Pascal case:
SomeName
- Snake case:
some_name
- Constant case:
SOME_NAME
- Param case:
some-name
(IMPORTANT: inside templates use<%= locals['some-name'] %>
)
If you need more options for your snippet you can create the options.json
file in snippet directory. (And remember: empty file = no file)
Example .snippets/src/components/Component.snippet/options.json
:
[
{
"type": "confirm",
"name": "styles",
"message": "With styles?"
},
{
"type": "confirm",
"name": "tests",
"message": "With unit tests?"
}
]