UNPKG

unplugin-copy

Version:

Copy files and folders, with glob support.

127 lines (118 loc) 3.29 kB
// src/index.ts import { createUnplugin } from "unplugin"; // src/core/buildFactory.ts import fs from "fs-extra"; // src/core/resolve.ts import path2 from "path/posix"; import process from "process"; import FastGlob from "fast-glob"; // src/core/utils.ts import path from "path"; function normalizePosixPath(id) { return path.posix.normalize(id.replace(/\\/g, "/")); } function isFunction(val) { return typeof val === "function"; } // src/core/resolve.ts function removeRepeat(list) { return [...new Set(list)]; } function resolveCopyTarget(targets) { const root = process.cwd(); const promises = targets.map(async (target) => { const dest = normalizePosixPath(target.dest); const globs = await FastGlob(target.src, { dot: true, cwd: root }); const dirPaths = removeRepeat(globs.map(path2.dirname)); let srcDir = ""; dirPaths.forEach((dirPath) => { if (srcDir === "" || !dirPath.includes(srcDir)) { srcDir = dirPath; } }); const resolves = globs.map((filePath) => { filePath = normalizePosixPath(filePath); const flatten = isFunction(target.flatten) ? !!target.flatten(filePath) : !!target.flatten; const destPath = normalizePosixPath( flatten ? path2.join(dest, path2.basename(filePath)) : path2.join(filePath.replace(srcDir, dest)) ); const rename = isFunction(target.rename) ? target.rename(filePath, destPath) : target.rename; return { src: filePath, dest: rename ? `${rename}` : destPath }; }); return { resolves, srcDir, destDir: dest }; }); return Promise.all(promises); } // src/core/buildFactory.ts var PLUGIN_NAME = "unplugin-copy:build"; var buildFactory = (options, _meta) => { let called = false; return { name: PLUGIN_NAME, vite: { apply: "build" }, async buildEnd() { if (called) { return; } called = true; const results = await resolveCopyTarget(options.targets); const resolves = results.map((e) => e.resolves).flat(); const promises = resolves.map(async (resolve) => { this.emitFile({ type: "asset", fileName: resolve.dest, source: await fs.readFile(resolve.src) }); }); await Promise.all(promises); } }; }; // src/core/viteServeFactory.ts import path3 from "path/posix"; import serveStatic from "serve-static"; var viteServeFactory = (options, _meta) => { let base = "/"; return { name: "unplugin-copy:serve", vite: { apply: "serve", configResolved(config) { base = normalizePosixPath(config.base || "/"); }, async configureServer(server) { const results = await resolveCopyTarget(options.targets); results.forEach((result) => { const route = path3.join("/", base, result.destDir); server.middlewares.use(route, serveStatic(result.srcDir)); }); } } }; }; // src/index.ts var unpluginFactory = (options, meta) => { return [ viteServeFactory(options, meta), buildFactory(options, meta) ]; }; var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory); var index_default = unplugin; export { unpluginFactory, unplugin, index_default };