shoelace/scripts/make-react.js

69 wiersze
2.1 KiB
JavaScript
Czysty Zwykły widok Historia

2022-01-26 13:46:20 +00:00
import commandLineArgs from 'command-line-args';
2021-11-04 11:27:18 +00:00
import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
2022-07-27 20:17:23 +00:00
import { deleteSync } from 'del';
2021-11-04 11:27:18 +00:00
import prettier from 'prettier';
import prettierConfig from '../prettier.config.cjs';
import { getAllComponents } from './shared.js';
2022-01-26 13:46:20 +00:00
const { outdir } = commandLineArgs({ name: 'outdir', type: String });
const reactDir = path.join('./src/react');
2021-11-04 11:27:18 +00:00
// Clear build directory
2022-07-27 20:17:23 +00:00
deleteSync(reactDir);
2022-01-26 13:46:20 +00:00
fs.mkdirSync(reactDir, { recursive: true });
2021-11-04 11:27:18 +00:00
// Fetch component metadata
2022-01-26 13:46:20 +00:00
const metadata = JSON.parse(fs.readFileSync(path.join(outdir, 'custom-elements.json'), 'utf8'));
2021-11-04 11:27:18 +00:00
const components = getAllComponents(metadata);
const index = [];
components.map(component => {
const tagWithoutPrefix = component.tagName.replace(/^sl-/, '');
2022-01-26 13:46:20 +00:00
const componentDir = path.join(reactDir, tagWithoutPrefix);
2021-11-04 11:27:18 +00:00
const componentFile = path.join(componentDir, 'index.ts');
2022-11-10 21:27:23 +00:00
const importPath = component.path;
const eventImports = (component.events || [])
.map(event => `import { ${event.eventName} } from '../../../src/events/events';`)
.join('\n');
const eventNameImport =
(component.events || []).length > 0 ? `import { type EventName } from '@lit-labs/react';` : ``;
const events = (component.events || [])
.map(event => `${event.reactName}: '${event.name}' as EventName<${event.eventName}>`)
.join(',\n');
2021-11-04 11:27:18 +00:00
fs.mkdirSync(componentDir, { recursive: true });
2021-11-04 11:27:18 +00:00
const source = prettier.format(
`
import * as React from 'react';
import { createComponent } from '@lit-labs/react';
import Component from '../../${importPath}';
${eventNameImport}
${eventImports}
export default createComponent({
tagName: '${component.tagName}',
elementClass: Component,
react: React,
events: {
2021-11-04 11:27:18 +00:00
${events}
}
});
2021-11-04 11:27:18 +00:00
`,
Object.assign(prettierConfig, {
parser: 'babel-ts'
})
);
2023-06-22 14:56:24 +00:00
index.push(`export { default as ${component.name} } from './${tagWithoutPrefix}/index.js';`);
2021-11-04 11:27:18 +00:00
fs.writeFileSync(componentFile, source, 'utf8');
});
// Generate the index file
2022-01-26 13:46:20 +00:00
fs.writeFileSync(path.join(reactDir, 'index.ts'), index.join('\n'), 'utf8');