react-edge-tts
Version:
Generate text-to-speech narration for React content using Microsoft Edge TTS
71 lines • 3.05 kB
JavaScript
const { declare } = require('@babel/helper-plugin-utils');
const fs = require('fs');
const path = require('path');
const t = require('@babel/types');
module.exports = declare((api) => {
api.assertVersion(7);
return {
name: 'react-edge-tts',
visitor: {
JSXElement(nodePath, state) {
const options = state.opts;
const outputDir = options.outputDir || 'narration-content';
// Check if this is a Narrate component
const openingElement = nodePath.node.openingElement;
if (!t.isJSXIdentifier(openingElement.name) || openingElement.name.name !== 'Narrate') {
return;
}
// Extract props
const props = openingElement.attributes.reduce((acc, attr) => {
if (!t.isJSXAttribute(attr) || !t.isJSXIdentifier(attr.name))
return acc;
const name = attr.name.name;
if (!attr.value)
return acc;
if (t.isStringLiteral(attr.value)) {
acc[name] = attr.value.value;
}
else if (t.isJSXExpressionContainer(attr.value) && t.isLiteral(attr.value.expression)) {
acc[name] = attr.value.expression.value;
}
return acc;
}, {});
// Extract text content
let content = '';
const extractTextContent = (node) => {
if (t.isJSXText(node)) {
content += node.value.trim();
}
else if (t.isJSXElement(node)) {
node.children.forEach(extractTextContent);
}
};
nodePath.node.children.forEach(extractTextContent);
if (!props.title || !content) {
return;
}
// Create narration content object
const narrationContent = {
metadata: {
title: props.title,
voice: props.voice,
rate: props.rate,
volume: props.volume,
pitch: props.pitch,
outputPath: props.outputPath,
},
content: content.trim(),
};
// Ensure output directory exists
const outputPath = path.join(process.cwd(), outputDir);
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}
// Write content to JSON file
const filename = `${props.title}.json`;
fs.writeFileSync(path.join(outputPath, filename), JSON.stringify(narrationContent, null, 2));
},
},
};
});
//# sourceMappingURL=plugin.js.map