70 lines
1.9 KiB
TypeScript
Raw Normal View History

import { assert } from "tsafe/assert";
2024-06-09 09:15:16 +02:00
import type { BuildContext } from "../../../shared/buildContext";
import { replaceImportsInJsCode_vite } from "./vite";
import { replaceImportsInJsCode_webpack } from "./webpack";
import * as fs from "fs";
2024-06-09 09:15:16 +02:00
export type BuildContextLike = {
projectBuildDirPath: string;
assetsDirPath: string;
urlPathname: string | undefined;
bundler: { type: "vite" } | { type: "webpack" };
};
2024-06-09 09:15:16 +02:00
assert<BuildContext extends BuildContextLike ? true : false>();
2024-05-20 15:48:51 +02:00
export function replaceImportsInJsCode(params: {
jsCode: string;
2024-06-09 09:15:16 +02:00
buildContext: BuildContextLike;
2024-05-20 15:48:51 +02:00
}) {
2024-06-09 09:15:16 +02:00
const { jsCode, buildContext } = params;
const { fixedJsCode } = (() => {
switch (buildContext.bundler.type) {
case "vite":
return replaceImportsInJsCode_vite({
jsCode,
2024-06-09 09:15:16 +02:00
buildContext,
2024-05-20 15:48:51 +02:00
basenameOfAssetsFiles: readAssetsDirSync({
2024-06-09 09:15:16 +02:00
assetsDirPath: params.buildContext.assetsDirPath
})
});
case "webpack":
return replaceImportsInJsCode_webpack({
jsCode,
2024-06-09 09:15:16 +02:00
buildContext
});
}
})();
return { fixedJsCode };
}
const { readAssetsDirSync } = (() => {
let cache:
| {
assetsDirPath: string;
basenameOfAssetsFiles: string[];
}
| undefined = undefined;
function readAssetsDirSync(params: { assetsDirPath: string }): string[] {
const { assetsDirPath } = params;
if (cache !== undefined && cache.assetsDirPath === assetsDirPath) {
return cache.basenameOfAssetsFiles;
}
const basenameOfAssetsFiles = fs.readdirSync(assetsDirPath);
cache = {
assetsDirPath,
basenameOfAssetsFiles
};
return basenameOfAssetsFiles;
}
return { readAssetsDirSync };
})();