Skip to content

Commit

Permalink
✨ oss上传并替换原来html中文件地址
Browse files Browse the repository at this point in the history
  • Loading branch information
lgldlk committed Jul 28, 2024
1 parent 89a9181 commit 32ae057
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 14 deletions.
55 changes: 43 additions & 12 deletions packages/vite-add-cdn-script/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { BuildOptions, PluginOption, UserConfig, normalizePath } from "vite";
import { EEnforce, IOptions } from "./types";
import { libName } from "./config";
import { getExternalScript } from "cdn-script-core";
import glob from "glob";

import * as glob from "glob";
import fs from "fs";
import path from "path";
function viteAddCdnScript(opt: IOptions): PluginOption {
const { customScript = {}, defaultCdns = ["jsdelivr", "unpkg"] } = opt;
let _config: UserConfig;
let buildConfig: BuildOptions | undefined = undefined;

let mainJsNames: string[] = [];
return {
name: libName,
enforce: EEnforce.PRE,
Expand All @@ -21,21 +23,50 @@ function viteAddCdnScript(opt: IOptions): PluginOption {
sequential: true,
order: "post",
async handler() {
if (!buildConfig || !opt.uploadFiles) return;
const outDirPath = normalizePath(path.resolve(normalizePath(buildConfig.outDir)));
const files = glob.sync(outDirPath + "/**/*", {
nodir: true,
dot: true,
ignore: "**/*.html",
});
// 上传文件
for (const file of files) {
opt.uploadFiles(file, {});
try {
if (!buildConfig || !opt.uploadFiles || !buildConfig.outDir || !mainJsNames.length) return;

const outDirPath = normalizePath(path.resolve(normalizePath(buildConfig.outDir)));

const files = glob.sync(outDirPath + "/**/*", {
nodir: true,
dot: true,
ignore: "**/*.html",
});

const upLoadRes = await Promise.all(
files.map(async (file) => ({
ossPath: await opt.uploadFiles!(file, {}),
fileName: file.slice(outDirPath.length + 1),
})),
);
// 替换本地文件名
const htmlFilePath = glob.sync(outDirPath + "**/*.html", {
nodir: true,
dot: true,
});
if (htmlFilePath.length === 0) return;
const htmlFile = htmlFilePath[0];
let html = fs.readFileSync(htmlFile, "utf-8");
for (const mainJsName of mainJsNames) {
const find = upLoadRes.find((item) => mainJsName.includes(item.fileName));
if (!find) continue;
html = html.replace(mainJsName, find.ossPath);
}
fs.writeFileSync(htmlFile, html);
} catch (error) {
console.error(`${libName} error:`, (error as Error).message);
process.exit(1);
}
},
},
async transformIndexHtml(html) {
if (!defaultCdns || defaultCdns.length === 0) throw new Error("defaultCdns不能为空");
// 获取打包结果中的本地的js名字
const inHtmlJsName = html.match(/(?<=<script.*src=(["|']))(?=[./])(.*?)\1/g);
if (inHtmlJsName) {
mainJsNames = inHtmlJsName.map((item) => item.slice(0, -1));
}
// 打印控制器
const external = _config.build?.rollupOptions?.external;
if (!external) return html;
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-add-cdn-script/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@ export interface IOptions {
retryTimes?: number;
defaultCdns?: PropertyCdn[];

uploadFiles?: (filePath: string, info: {}) => {};
uploadFiles?: (filePath: string, info: {}) => string | Promise<string>;
}
9 changes: 8 additions & 1 deletion packages/vite-add-cdn-script/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ const pageConfig = {
server: {
port: 6101,
},
plugins: [react(), viteAddCdnScript({})],
plugins: [
react(),
viteAddCdnScript({
uploadFiles: () => {
return "tmp.com/xxx";
},
}),
],
base: "./",
build: {
outDir: "dist-page",
Expand Down

0 comments on commit 32ae057

Please sign in to comment.