@naoufal/create-react-component
Version:
The fastest way to create React Components
71 lines (62 loc) • 2.27 kB
JavaScript
const path = require('path');
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs-extra'));
const streamToPromise = require('stream-to-promise');
const { green } = require('chalk');
const {
walk,
outputFileAsync,
emptyDirAsync,
readdirAsync,
readFileAsync,
copyAsync,
lstatSync
} = fs;
const { getTemplates } = require('./helpers');
const TMP_DIR = path.join(__dirname, '../tmp');
function execution(options) {
const { componentName, componentPath, componentType, selectedTemplate } = options;
const template = getTemplates()
.find(template => template.name === selectedTemplate);
const templatePath = path.join(template.path, `/templates/${componentType}`);
// Create or empty `tmp` directory
return emptyDirAsync(TMP_DIR)
// Walk through template directory
.then(() => streamToPromise(walk(templatePath)))
// Copy and rename files to from the template to `tmp`
.map(file => {
const newFilePath = file.path
.replace(templatePath, TMP_DIR)
.replace(/COMPONENT_NAME/g, componentName);
const isDirectory = lstatSync(file.path).isDirectory();
// Skip if directory because `outputFile` will create directories for us
if (isDirectory) {
return;
}
return readFileAsync(file.path, 'utf8')
// Insert the Component name in template file
.then(fileContent => fileContent.replace(/COMPONENT_NAME/g, componentName))
// Write file to `tmp` directory
.then(newFileContent => outputFileAsync(newFilePath, newFileContent, 'utf8'));
})
// Read `tmp` directory to obtain the file name of the Component.
// This is done to support directories and various file extensions
.then(() => readdirAsync(TMP_DIR))
// Remove `.DS_Store` files
.filter(fileName => fileName !== '.DS_Store')
// Copy Component from `tmp` to final destination
.spread(fileName => {
const finalDestination = path.join(process.cwd(), componentPath, fileName);
return copyAsync(path.join(TMP_DIR, fileName), finalDestination)
.then(() => finalDestination);
})
// Display success message
.then(finalDestination => {
console.log(green(
` Successfully created your component at ${finalDestination}\n\n`
));
});
}
module.exports = {
execution
};