Skip to content

Instantly share code, notes, and snippets.

@Silverium
Last active February 28, 2019 17:50
Show Gist options
  • Save Silverium/ad3135034308615813b364aabc045b90 to your computer and use it in GitHub Desktop.
Save Silverium/ad3135034308615813b364aabc045b90 to your computer and use it in GitHub Desktop.
Node script that reads the vue SFC files of all the tree of a directory and reorders their script, template and style tags
// execute it with command "node orderScriptAndTemplateTagsInSFC.js [ <dir> ]"
const fs = require('fs');
function orderScriptAndTemplateTagsInSFC() {
// 1. Read files / directories of path given to the script through parameter and create an array.
const directory = process.argv[2] || __dirname;
const paths = fs.readdirSync(directory)
.filter(filepath => !filepath.match(/^\./)); // remove hidden files or folders
const isVue = filepath => /.*\.vue$/.test(filepath);
const isDir = filepath => fs.statSync(filepath).isDirectory();
const templateTag = string => string.match(/<template.*<\/template>/sg);
const scriptTag = string => string.match(/<script.*<\/script>/sg);
const styleTag = string => string.match(/<style.*<\/style>/sg);
// 4. Arrange <script> and <template> in file, allocate <script> in the beginning of file, then <template>, then the <style>
const allocateScriptFirst = (filepath) => {
fs.readFile(filepath, 'utf8', (err, vueFile) => {
if (err) {
console.info(err);
}
const templatePart = templateTag(vueFile) || [];
const scriptPart = scriptTag(vueFile) || [];
const stylePart = styleTag(vueFile) || [];
// adding correct formatting for linter
const reorderedVueFile = `${scriptPart.concat(templatePart, stylePart).join('\n\n')}\n`;
fs.writeFile(filepath, reorderedVueFile, 'utf8', (error) => {
if (error) return console.info(error);
return 'done';
});
});
};
const shufflePaths = (iterator, currentPath) => {
// 2. if Array has no length, we finished, otherwise, get the first filepath by Array.shift method and shuffle depending on file type
if (!(iterator && iterator.length)) return;
const item = iterator.shift();
const filepath = `${currentPath}/${item}`;
if (isDir(filepath)) { // 3. isFolder ? goToStep1 : goToStep3
shufflePaths(fs.readdirSync(`${filepath}/`), filepath);
} else if (isVue(item)) { // 3. isVue ? goToStep4 : goToStep2
allocateScriptFirst(filepath);
}
shufflePaths(iterator, currentPath);
};
// initiate recursive function
shufflePaths(paths, `${directory}`);
}
orderScriptAndTemplateTagsInSFC();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment