storybook/scripts/utils/compile-babel.js

111 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-01-28 19:17:13 +02:00
/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
const shell = require('shelljs');
function getCommand(watch, dir) {
2019-07-22 06:33:57 +00:00
// Compile angular with tsc
2019-05-20 14:05:15 +02:00
if (process.cwd().includes(path.join('app', 'angular'))) {
return '';
}
2020-12-09 09:42:03 +01:00
if (process.cwd().includes(path.join('addons', 'storyshots'))) {
return '';
}
2019-05-20 14:05:15 +02:00
2020-05-09 11:34:50 +02:00
const babel = path.join(__dirname, '..', '..', 'node_modules', '.bin', 'babel');
2018-01-29 00:57:51 +02:00
2019-03-23 23:09:01 +01:00
const args = [
2018-12-28 01:39:01 +01:00
'./src',
`--out-dir ${dir}`,
2020-05-09 11:34:50 +02:00
`--config-file ${path.resolve(__dirname, '../../.babelrc.js')}`,
2018-12-28 01:39:01 +01:00
`--copy-files`,
];
/*
* angular needs to be compiled with tsc; a compilation with babel is possible but throws
* runtime errors because of the the babel decorators plugin
* Only transpile .js and let tsc do the job for .ts files
*/
2019-05-20 14:05:15 +02:00
if (process.cwd().includes(path.join('addons', 'storyshots'))) {
args.push(`--extensions ".js"`);
} else {
args.push(`--extensions ".js,.jsx,.ts,.tsx"`);
}
if (watch) {
args.push('-w');
}
2018-01-29 00:57:51 +02:00
return `${babel} ${args.join(' ')}`;
}
function handleExit(code, stderr, errorCallback) {
if (code !== 0) {
2018-01-28 19:09:40 +02:00
if (errorCallback && typeof errorCallback === 'function') {
errorCallback(stderr);
2018-01-28 19:09:40 +02:00
}
shell.exit(code);
}
}
async function run({ watch, dir, silent, errorCallback }) {
return new Promise((resolve, reject) => {
const command = getCommand(watch, dir);
if (command !== '') {
const child = shell.exec(command, {
async: true,
silent,
env: { ...process.env, BABEL_ESM: dir.includes('esm') },
});
let stderr = '';
child.stderr.on('data', (data) => {
stderr += data.toString();
});
child.stdout.on('data', (data) => {
console.log(data);
});
child.on('exit', (code) => {
resolve();
handleExit(code, stderr, errorCallback);
});
} else {
resolve();
}
});
}
async function babelify(options = {}) {
const { watch = false, silent = true, modules, errorCallback } = options;
2018-01-29 00:57:51 +02:00
if (!fs.existsSync('src')) {
2019-03-04 11:56:27 +01:00
if (!silent) {
console.log('No src dir');
}
2018-01-29 00:57:51 +02:00
return;
}
if (watch) {
await Promise.all([
run({ watch, dir: './dist/cjs', silent, errorCallback }),
modules ? run({ watch, dir: './dist/esm', silent, errorCallback }) : Promise.resolve(),
]);
} else {
// cjs
2020-12-09 09:42:03 +01:00
await run({ dir: './dist/cjs', silent, errorCallback });
if (modules) {
// esm
await run({ dir: './dist/esm', silent, errorCallback });
}
2019-05-20 14:05:15 +02:00
}
2018-01-29 00:57:51 +02:00
}
module.exports = {
babelify,
};