cli is where the scripts are executed when the user runs a CLI command
docs is the folder that houses markdown files
scripts is the folder that houses scripts, containing the logic of the operations
templates is the folder that houses templates for the new files
Note: The separation of cli and scripts enables us to extract and write unit tests for the core logic, without having to worry about the execution context (via a command line or via an outer function call).
Implementation
Creating a template
First of, we need to create a new template in the templates folder:
Adding a command to package.json
We add the gen-doc command to package.json:
When the user runs npm run gen-doc, the ./cli/gen-doc.ts file will be executed.
Adding a script for the file gen operation
Within scripts, we create a gen-doc.ts file and define a genDoc function that handles the file generation. The function accepts fileName as an argument, then transforms and passes it to the template.
Handling the gen-doc command
The last step is to create a genDoc.ts file in the cli folder. When the user runs npm run gen-doc [fileName], this file is executed, extracts the provided fileName, and calls the genDoc function from the script:
Testing
Manual testing
We can test the CLI by running the following command in the terminal:
A new my-doc.md file should be created in the docs folder.
Unit testing
As previously mentioned, we are going to write tests for the core logic, which is the genDoc function in script/gen-doc.ts. The fs module is mocked with memfs to prevent the tests from writing to the real file system.
Within the scripts folder, create a gen-doc.test.ts file as follows: