@tsbb/babel
Version:
TSBB is a zero-config CLI that helps you develop, test, and publish modern TypeScript project.
81 lines (80 loc) • 3.34 kB
JavaScript
import fs from 'fs-extra';
import path from 'node:path';
import { Log, getEmojiIcon, getExt } from '@tsbb/typescript';
import babelPluginJsx from '@vue/babel-plugin-jsx';
import { transform } from './transform.js';
import { getOutputPath } from './utils.js';
import { getCjsTransformOption, getESMTransformOption } from './config.js';
export * from './utils.js';
export default async function compile(fileName, options = {}) {
const { cjs = 'lib', esm = 'esm', envName, useVue = false, bail, watch } = options;
const dt = getOutputPath(fileName, options);
const log = new Log();
log.name();
if (options.sourceMaps === 'true') {
options.sourceMaps = true;
}
let esmBabelOptions = getESMTransformOption();
if (useVue) {
// @ts-ignore
esmBabelOptions.plugins?.push(babelPluginJsx.default);
}
if (envName) {
esmBabelOptions = {};
esmBabelOptions.envName = envName;
}
esmBabelOptions.sourceMaps = options.sourceMaps || esmBabelOptions.sourceMaps;
esmBabelOptions.babelrc = true;
esmBabelOptions.cwd = dt.projectDirectory;
if (typeof esm === 'string') {
transformFile(fileName, dt.esm.path, dt.folderFilePath, dt.projectDirectory, dt.esm.fileName, esmBabelOptions, bail, watch);
}
let cjsBabelOptions = getCjsTransformOption();
if (useVue) {
// @ts-ignore
cjsBabelOptions.plugins?.push(babelPluginJsx.default);
}
if (envName) {
cjsBabelOptions = {};
cjsBabelOptions.envName = envName;
}
cjsBabelOptions.sourceMaps = options.sourceMaps || cjsBabelOptions.sourceMaps;
cjsBabelOptions.babelrc = true;
cjsBabelOptions.cwd = dt.projectDirectory;
if (typeof cjs === 'string') {
transformFile(fileName, dt.cjs.path, dt.folderFilePath, dt.projectDirectory, dt.cjs.fileName, cjsBabelOptions, bail, watch);
}
}
function transformFile(fileName, outputFile, folderFilePath, projectDirectory, outFileName, options, bail, isWatch) {
const log = new Log();
log.name();
options.sourceFileName = path.relative(path.dirname(outputFile), fileName);
transform(fileName, { ...options })
.then((result) => {
fs.ensureFileSync(outputFile);
fs.writeFile(outputFile, result?.code || '');
log
.icon(getEmojiIcon(outputFile))
.success(`${getExt(outFileName)}┈┈▶ \x1b[33;1m${folderFilePath}\x1b[0m => \x1b[33;1m${outFileName}\x1b[0m`);
if (options.sourceMaps === 'both' || options.sourceMaps) {
if (result?.map) {
const sourceMapPath = path.join(outputFile + '.map');
fs.writeFileSync(sourceMapPath, JSON.stringify(result?.map, null, 2));
log
.icon(getEmojiIcon(outputFile))
.success(`┈┈▶ \x1b[33;1m${folderFilePath}\x1b[0m => \x1b[33;1m${path.relative(projectDirectory, sourceMapPath)}\x1b[0m`);
}
}
})
.catch((error) => {
if (error instanceof Error) {
log.icon('\n🚨').error(`\x1b[33;1m ${error.message}\x1b[0m\n`);
}
else {
log.icon('\n🚨').error(`\x1b[33;1m ${JSON.stringify(error)}\x1b[0m\n`);
}
if (bail && isWatch !== true) {
process.exitCode = 1;
}
});
}