UNPKG

@chubbyts/chubbyts-packaging

Version:
59 lines (58 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.renameAndMoveJsFiles = exports.getAllFiles = exports.fixModuleImportPaths = exports.fixCommonjsRequirePaths = void 0; const child_process_1 = require("child_process"); const fs_1 = require("fs"); const path_1 = require("path"); const fixCommonjsRequirePaths = (code) => code.replace(/(?<=\brequire\(['"])(\.\.?\/[^'"]+?)(?:\.js|\.cjs)?(?=['"])/g, '$1.cjs'); exports.fixCommonjsRequirePaths = fixCommonjsRequirePaths; const fixModuleImportPaths = (code) => code.replace(/(?<=\bimport(?:\s+.+?from\s+|(?:\s*\())['"])(\.\.?\/[^'"]+?)(?:\.js|\.mjs)?(?=['"])/g, '$1.mjs'); exports.fixModuleImportPaths = fixModuleImportPaths; const getAllFiles = (path) => { return (0, fs_1.readdirSync)(path) .map((file) => { const filePath = path + '/' + file; if ((0, fs_1.statSync)(filePath).isDirectory()) { return (0, exports.getAllFiles)(filePath); } return [filePath]; }) .flat(); }; exports.getAllFiles = getAllFiles; const renameAndMoveJsFiles = (path, fileEnding, fixPaths) => { const fileEndingSubPath = path + '/' + fileEnding; (0, exports.getAllFiles)(fileEndingSubPath).map((file) => { const name = (0, path_1.basename)(file); const fromFolder = (0, path_1.dirname)(file); const fromPath = fromFolder + '/' + name; if (!name.match(/\.js$/)) { throw new Error(`"${fromPath}" is not a js file. Please add it with tools like copyfiles after the build.`); } const toFolder = path + fromFolder.substring(fileEndingSubPath.length); if (!(0, fs_1.existsSync)(toFolder)) { (0, fs_1.mkdirSync)(toFolder, { recursive: true }); } const toPath = toFolder + '/' + name.replace(/\.js$/, '.' + fileEnding); (0, fs_1.writeFileSync)(toPath, fixPaths((0, fs_1.readFileSync)(fromPath, { encoding: 'utf8', flag: 'r' }))); }); (0, fs_1.rmSync)(fileEndingSubPath, { recursive: true, force: true }); }; exports.renameAndMoveJsFiles = renameAndMoveJsFiles; ///////////////////////////////////////////////////////////////////////////////////////////////// /* c8 ignore next 10000 */ const distDir = './dist'; const commonJsFileEnding = 'cjs'; const moduleFileEnding = 'mjs'; (0, fs_1.rmSync)(distDir, { recursive: true, force: true }); try { (0, child_process_1.execSync)(`./node_modules/.bin/tsc --module commonjs --outDir ${distDir}/${commonJsFileEnding}`); (0, child_process_1.execSync)(`./node_modules/.bin/tsc --module esnext --outDir ${distDir}/${moduleFileEnding}`); (0, child_process_1.execSync)(`./node_modules/.bin/tsc --declaration --emitDeclarationOnly --outDir ${distDir}`); } catch (e) { console.log(e?.toString()); process.exit(1); } (0, exports.renameAndMoveJsFiles)(distDir, commonJsFileEnding, exports.fixCommonjsRequirePaths); (0, exports.renameAndMoveJsFiles)(distDir, moduleFileEnding, exports.fixModuleImportPaths);