UNPKG

create-bfe-cttq

Version:

CTTQ大前端脚手架项目

57 lines (49 loc) 1.85 kB
const fs = require('fs') const path = require('path') const deepMerge = require("./deepMerge.js") const sortDependencies = require("./sortDependencies.js") /** * Renders a template folder/file to the file system, * by recursively copying all files under the `src` directory, * with the following exception: * - `_filename` should be renamed to `.filename` * - Fields in `package.json` should be recursively merged * @param {string} src source filename to copy * @param {string} dest destination filename of the copy operation */ function renderTemplate(src, dest, excludes = []) { let excludesFile = (excludes || []).filter((item) => src.endsWith(item)); if (excludesFile.length > 0) { return; } const stats = fs.statSync(src); const filename = path.basename(src); if (filename.startsWith("_") && !filename.startsWith("__")) { // rename `_file` to `.file` dest = path.resolve(path.dirname(dest), filename.replace(/^_/, ".")); } else if (filename.startsWith("__")) { dest = path.resolve(path.dirname(dest), filename.replace(/^_/, "")); } if (stats.isDirectory()) { // skip node_module if (filename === "node_modules") { return; } // if it's a directory, render its subdirectories and files recursively fs.mkdirSync(dest, { recursive: true }); for (const file of fs.readdirSync(src)) { renderTemplate(path.resolve(src, file), path.resolve(dest, file), excludes); } return; } if (filename === "package.json" && fs.existsSync(dest)) { // merge instead of overwriting const existing = JSON.parse(fs.readFileSync(dest, "utf8")); const newPackage = JSON.parse(fs.readFileSync(src, "utf8")); const pkg = sortDependencies(deepMerge(existing, newPackage)); fs.writeFileSync(dest, JSON.stringify(pkg, null, 2) + "\n"); return; } fs.copyFileSync(src, dest); } module.exports = renderTemplate;