|
// 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(); |