Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/hook config #1108

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 33 additions & 15 deletions packages/cli/src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ import {
MitosisConfig,
parseJsx,
Target,
TranspilerGenerator,
parseSvelte,
TargetContext,
OutputFiles,
} from '@builder.io/mitosis';
import debug from 'debug';
import { flow, pipe } from 'fp-ts/lib/function';
import { outputFile, pathExists, readFile, remove } from 'fs-extra';
import { kebabCase } from 'lodash';
import { kebabCase, get } from 'lodash';
import { fastClone } from '../helpers/fast-clone';
import { generateContextFile } from './helpers/context';
import { getFileExtensionForTarget } from './helpers/extensions';
Expand Down Expand Up @@ -192,12 +193,6 @@ const getMitosisComponentJSONs = async (options: MitosisConfig): Promise<ParsedM
);
};

interface TargetContext {
target: Target;
generator: TranspilerGenerator<MitosisConfig['options'][Target]>;
outputPath: string;
}

interface TargetContextWithConfig extends TargetContext {
options: MitosisConfig;
}
Expand All @@ -216,6 +211,22 @@ const buildAndOutputNonComponentFiles = async (targetContext: TargetContextWithC
return await outputNonComponentFiles({ ...targetContext, files });
};

function runHook(hook: string, config?: MitosisConfig) {
PengBoUESTC marked this conversation as resolved.
Show resolved Hide resolved
const noop = () => {};
const hookFn = get(config, `hooks.${hook}`);
PengBoUESTC marked this conversation as resolved.
Show resolved Hide resolved

if (!hookFn) {
return noop;
}
const debugTarget = debug(`mitosis:${hook}`);

return async (...params) => {
debugTarget(`before run ${hook} hook...`);
await hookFn(...params);
debugTarget(`after run ${hook} hook`);
};
}

export async function build(config?: MitosisConfig) {
// merge default options
const options = getOptions(config);
Expand All @@ -227,6 +238,7 @@ export async function build(config?: MitosisConfig) {
const mitosisComponents = await getMitosisComponentJSONs(options);

const targetContexts = getTargetContexts(options);
await runHook('beforeBuild')(targetContexts);

await Promise.all(
targetContexts.map(async (targetContext) => {
Expand All @@ -238,7 +250,10 @@ export async function build(config?: MitosisConfig) {
buildAndOutputNonComponentFiles({ ...targetContext, options }),
buildAndOutputComponentFiles({ ...targetContext, options, files }),
]);

await runHook('afterbuild')(targetContext, {
componentFiles: x[1],
nonComponentFiles: x[0],
});
console.info(
`Mitosis: ${targetContext.target}: generated ${x[1].length} components, ${x[0].length} regular files.`,
);
Expand Down Expand Up @@ -326,7 +341,7 @@ async function buildAndOutputComponentFiles({
options,
generator,
outputPath,
}: TargetContextWithConfig & { files: ParsedMitosisJson[] }) {
}: TargetContextWithConfig & { files: ParsedMitosisJson[] }): Promise<OutputFiles[]> {
const debugTarget = debug(`mitosis:${target}`);
const shouldOutputTypescript = checkShouldOutputTypeScript({ options, target });

Expand Down Expand Up @@ -368,6 +383,7 @@ async function buildAndOutputComponentFiles({
const outputDir = `${options.dest}/${outputPath}`;

await outputFile(`${outputDir}/${outputFilePath}`, transpiled);
return { outputDir, outputFilePath };
});
return await Promise.all(output);
}
Expand All @@ -387,13 +403,15 @@ const outputNonComponentFiles = async ({
}: TargetContext & {
files: { path: string; output: string }[];
options: MitosisConfig;
}) => {
}): Promise<OutputFiles[]> => {
const extension = getNonComponentFileExtension({ target, options });
const folderPath = `${options.dest}/${outputPath}`;
const outputDir = `${options.dest}/${outputPath}`;
return await Promise.all(
files.map(({ path, output }) =>
outputFile(`${folderPath}/${path.replace(/\.tsx?$/, extension)}`, output),
),
files.map(async ({ path, output }) => {
const outputFilePath = path.replace(/\.tsx?$/, extension);
await outputFile(`${outputDir}/${outputFilePath}`, output);
return { outputDir, outputFilePath };
}),
);
};

Expand Down
26 changes: 26 additions & 0 deletions packages/core/src/types/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { MitosisComponent } from './mitosis-component';
import { TranspilerGenerator } from './transpiler';

export type Format = 'esm' | 'cjs';
export type Language = 'js' | 'ts';
Expand All @@ -14,6 +15,17 @@ export type GeneratorOptions = {
};
};

export interface TargetContext {
target: Target;
generator: TranspilerGenerator<NonNullable<MitosisConfig['options'][Target]>>;
outputPath: string;
}

export interface OutputFiles {
outputDir: string;
outputFilePath: string;
}

export type MitosisConfig = {
/**
* List of targets to compile to.
Expand Down Expand Up @@ -58,6 +70,20 @@ export type MitosisConfig = {
* ```
*/
options: Partial<GeneratorOptions>;

/**
* hooks
*/
hooks?: Partial<{
beforeBuild: (TargetContexts: TargetContext[]) => void | Promise<void>;
afterbuild: (
TargetContext: TargetContext,
files: {
componentFiles: OutputFiles[];
nonComponentFiles: OutputFiles[];
},
) => void | Promise<void>;
}>;
/**
* Configure a custom parser function which takes a string and returns MitosisJSON
* Defaults to the JSXParser of this project (src/parsers/jsx)
Expand Down