Skip to content

Instantly share code, notes, and snippets.

@3vorp
Last active July 16, 2024 18:48
Show Gist options
  • Save 3vorp/24c8fc1d560235f3c4dbbd69f9d4ca4d to your computer and use it in GitHub Desktop.
Save 3vorp/24c8fc1d560235f3c4dbbd69f9d4ca4d to your computer and use it in GitHub Desktop.
Convert JS Vue template strings to Vue SFC files. Doesn't handle formatting, imports, and the templates have to be in backticks to work, but it can bulk edit an entire project.
import { readdirSync, statSync, readFileSync, mkdirSync, existsSync, writeFileSync } from "fs";
import { sep } from "path";
const INPUT_JS_PATH = "./pages";
const EMITTED_VUE_PATH = "./vue";
function walkSync(dir: string, filelist: string[] = []) {
// add trailing slash if not present
if (!dir.endsWith(sep)) dir += sep;
for (const file of readdirSync(dir)) {
if (statSync(dir + file).isDirectory())
// read directories inside directories recursively
filelist = walkSync(dir + file + sep, filelist);
else filelist.push(dir + file);
}
return filelist;
}
function jsToVue(originalContents: string): string {
const [top, middleBottom] = originalContents.split("template: `");
const [middle, ...bottom] = middleBottom.split("`,");
const out = `<template>${middle}</template>\n\n<script>\n${top}${bottom.join("`,")}</script>`;
return out;
}
function fixPath(path: string): string {
const out = path.replace(INPUT_JS_PATH, EMITTED_VUE_PATH).replace(".js", ".vue");
const dir = out.split("/").slice(0, -1).join("/");
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
return out;
}
const paths = walkSync(INPUT_JS_PATH).filter((v) => v.endsWith("js"));
if (!existsSync(EMITTED_VUE_PATH)) mkdirSync(EMITTED_VUE_PATH);
for (const path of paths) {
const originalContents = readFileSync(path, { encoding: "utf8" });
const out = jsToVue(originalContents);
writeFileSync(fixPath(path), out);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment