|
| 1 | +import * as fs from "fs"; |
| 2 | +import { posix as path } from "path"; |
| 3 | + |
| 4 | +export type SupportModuleType = "browser" | "node" | "require" | "import" | "default"; |
| 5 | + |
| 6 | +export type SupportModule = { |
| 7 | + // eslint-disable-next-line no-unused-vars |
| 8 | + [P in SupportModuleType]?: string; |
| 9 | +}; |
| 10 | + |
| 11 | +export interface Option { |
| 12 | + directory: Partial<SupportModule>; |
| 13 | +} |
| 14 | + |
| 15 | +export interface ExportsField { |
| 16 | + [filepath: string]: SupportModule; |
| 17 | +} |
| 18 | + |
| 19 | +const isFile = (p: string) => { |
| 20 | + return fs.existsSync(p) && fs.statSync(p).isFile(); |
| 21 | +}; |
| 22 | + |
| 23 | +const isTypeScriptFile = (p: string): boolean => { |
| 24 | + return !!p.match(/tsx?$/); |
| 25 | +}; |
| 26 | + |
| 27 | +const isIndexFile = (p: string) => { |
| 28 | + return !!p.match(/index\.tsx?$/); |
| 29 | +}; |
| 30 | + |
| 31 | +const convertNameTsToJs = (p: string): string => { |
| 32 | + return p.replace(/\.tsx?$/, ".js"); |
| 33 | +}; |
| 34 | + |
| 35 | +const isSupportModuleType = (text: string | undefined): text is SupportModuleType => { |
| 36 | + if (!text) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + return ["node", "browser", "require", "import", "default"].includes(text); |
| 40 | +}; |
| 41 | + |
| 42 | +const trimExtension = (p: string): string => { |
| 43 | + const ext = path.extname(p); |
| 44 | + return p.replace(new RegExp(ext + "$"), ""); |
| 45 | +}; |
| 46 | + |
| 47 | +export const generateExportsField = (sourceRootDirectory: string, option: Option): ExportsField => { |
| 48 | + const pathArray = fs.readdirSync(sourceRootDirectory); |
| 49 | + const filteredPathArray = pathArray.filter(p => { |
| 50 | + const pathName = path.join(sourceRootDirectory, p); |
| 51 | + return isTypeScriptFile(pathName) && isFile(pathName); |
| 52 | + }); |
| 53 | + return filteredPathArray.reduce<ExportsField>((exportsFields, pathName) => { |
| 54 | + const filepath = isIndexFile(pathName) ? "." : "./" + trimExtension(pathName); |
| 55 | + const jsFilename = convertNameTsToJs(pathName); |
| 56 | + const supportModule: SupportModule = {}; |
| 57 | + Object.entries(option.directory).forEach(([key, exportBaseDirectory]) => { |
| 58 | + if (isSupportModuleType(key) && typeof exportBaseDirectory === "string") { |
| 59 | + supportModule[key] = "./" + path.join(exportBaseDirectory, jsFilename); |
| 60 | + } |
| 61 | + }); |
| 62 | + return { ...exportsFields, [filepath]: supportModule }; |
| 63 | + }, {}); |
| 64 | +}; |
0 commit comments