feat: support projectRemark which added in globalContextData

This commit is contained in:
LeoYuan 袁力皓 2022-12-20 10:49:32 +08:00 committed by eternalsky
parent 995b11a073
commit deeeed29ab
5 changed files with 52 additions and 14 deletions

View File

@ -90,31 +90,34 @@ export class ProjectBuilder implements IProjectBuilder {
async generateProject(originalSchema: ProjectSchema | string): Promise<ResultDir> { async generateProject(originalSchema: ProjectSchema | string): Promise<ResultDir> {
// Init // Init
const { schemaParser } = this; const { schemaParser } = this;
const builders = this.createModuleBuilders();
const projectRoot = await this.template.generateTemplate(); const projectRoot = await this.template.generateTemplate();
let schema: ProjectSchema = let schema: ProjectSchema =
typeof originalSchema === 'string' ? JSON.parse(originalSchema) : originalSchema; typeof originalSchema === 'string' ? JSON.parse(originalSchema) : originalSchema;
// Validate
if (!schemaParser.validate(schema)) {
throw new CodeGeneratorError('Schema is invalid');
}
// Parse / Format // Parse / Format
// Preprocess // Preprocess
for (const preProcessor of this.projectPreProcessors) { for (const preProcessor of this.projectPreProcessors) {
// eslint-disable-next-line no-await-in-loop // eslint-disable-next-line no-await-in-loop
schema = await preProcessor(schema); schema = await preProcessor(schema);
} }
// Validate
if (!schemaParser.validate(schema)) {
throw new CodeGeneratorError('Schema is invalid');
}
// Collect Deps // Collect Deps
// Parse JSExpression // Parse JSExpression
const parseResult: IParseResult = schemaParser.parse(schema); const parseResult: IParseResult = schemaParser.parse(schema);
let buildResult: IModuleInfo[] = []; let buildResult: IModuleInfo[] = [];
const builders = this.createModuleBuilders({
extraContextData: {
projectRemark: parseResult?.project?.projectRemark,
},
});
// Generator Code module // Generator Code module
// components // components
// pages // pages
@ -253,11 +256,12 @@ export class ProjectBuilder implements IProjectBuilder {
// TODO: 更多 slots 的处理??是不是可以考虑把 template 中所有的 slots 都处理下? // TODO: 更多 slots 的处理??是不是可以考虑把 template 中所有的 slots 都处理下?
// Post Process // Post Process
const isSingleComponent = parseResult?.project?.projectRemark?.isSingleComponent;
// Combine Modules // Combine Modules
buildResult.forEach((moduleInfo) => { buildResult.forEach((moduleInfo) => {
let targetDir = getDirFromRoot(projectRoot, moduleInfo.path); let targetDir = getDirFromRoot(projectRoot, moduleInfo.path);
if (moduleInfo.moduleName) { // if project only contain single component, skip creation of directory.
if (moduleInfo.moduleName && !isSingleComponent) {
const dir = createResultDir(moduleInfo.moduleName); const dir = createResultDir(moduleInfo.moduleName);
addDirectory(targetDir, dir); addDirectory(targetDir, dir);
targetDir = dir; targetDir = dir;
@ -278,7 +282,8 @@ export class ProjectBuilder implements IProjectBuilder {
return finalResult; return finalResult;
} }
private createModuleBuilders(): Record<string, IModuleBuilder> { private createModuleBuilders(extraContextData: Record<string, unknown> = {}):
Record<string, IModuleBuilder> {
const builders: Record<string, IModuleBuilder> = {}; const builders: Record<string, IModuleBuilder> = {};
Object.keys(this.plugins).forEach((pluginName) => { Object.keys(this.plugins).forEach((pluginName) => {
@ -291,10 +296,12 @@ export class ProjectBuilder implements IProjectBuilder {
plugins: this.plugins[pluginName], plugins: this.plugins[pluginName],
postProcessors: this.postProcessors, postProcessors: this.postProcessors,
contextData: { contextData: {
// template: this.template,
inStrictMode: this.inStrictMode, inStrictMode: this.inStrictMode,
tolerateEvalErrors: true, tolerateEvalErrors: true,
evalErrorsHandler: '', evalErrorsHandler: '',
...this.extraContextData, ...this.extraContextData,
...extraContextData,
}, },
...options, ...options,
}); });

View File

@ -36,6 +36,7 @@ import { handleSubNodes, isValidContainerType } from '../utils/schema';
import { uniqueArray } from '../utils/common'; import { uniqueArray } from '../utils/common';
import { componentAnalyzer } from '../analyzer/componentAnalyzer'; import { componentAnalyzer } from '../analyzer/componentAnalyzer';
import { ensureValidClassName } from '../utils/validate'; import { ensureValidClassName } from '../utils/validate';
import type { ProjectRemark } from '../types/intermediate';
const defaultContainer: IContainerInfo = { const defaultContainer: IContainerInfo = {
containerType: 'Component', containerType: 'Component',
@ -319,10 +320,17 @@ export class SchemaParser implements ISchemaParser {
utilsDeps, utilsDeps,
packages: npms || [], packages: npms || [],
dataSourcesTypes: this.collectDataSourcesTypes(schema), dataSourcesTypes: this.collectDataSourcesTypes(schema),
projectRemark: this.getProjectRemark(containers),
}, },
}; };
} }
getProjectRemark(containers: IContainerInfo[]): ProjectRemark {
return {
isSingleComponent: containers.length === 1 && containers[0].containerType === 'Component',
};
}
getComponentNames(children: NodeDataType): string[] { getComponentNames(children: NodeDataType): string[] {
return handleSubNodes<string>( return handleSubNodes<string>(
children, children,

View File

@ -27,7 +27,7 @@ import {
import { generateCompositeType } from '../../../utils/compositeType'; import { generateCompositeType } from '../../../utils/compositeType';
import { parseExpressionConvertThis2Context } from '../../../utils/expressionParser'; import { parseExpressionConvertThis2Context } from '../../../utils/expressionParser';
import { isContainerSchema } from '../../../utils/schema'; import { isValidContainerType } from '../../../utils/schema';
import { REACT_CHUNK_NAME } from './const'; import { REACT_CHUNK_NAME } from './const';
export interface PluginConfig { export interface PluginConfig {
@ -67,7 +67,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
}; };
const scope = Scope.createRootScope(); const scope = Scope.createRootScope();
const dataSourceConfig = isContainerSchema(pre.ir) ? pre.ir.dataSource : null; const dataSourceConfig = isValidContainerType(pre.ir) ? pre.ir.dataSource : null;
const dataSourceItems: InterpretDataSourceConfig[] = const dataSourceItems: InterpretDataSourceConfig[] =
(dataSourceConfig && dataSourceConfig.list) || []; (dataSourceConfig && dataSourceConfig.list) || [];
const dataSourceEngineOptions = { runtimeConfig: true }; const dataSourceEngineOptions = { runtimeConfig: true };

View File

@ -11,6 +11,7 @@ import {
FileType, FileType,
ICodeStruct, ICodeStruct,
IContainerInfo, IContainerInfo,
IProjectTemplate,
} from '../../../types'; } from '../../../types';
export interface PluginConfig { export interface PluginConfig {
@ -32,6 +33,19 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
next.contextData.useRefApi = true; next.contextData.useRefApi = true;
const useRef = !!ir.analyzeResult?.isUsingRef; const useRef = !!ir.analyzeResult?.isUsingRef;
// const isSingleComponent = next.contextData?.projectRemark?.isSingleComponent;
// const template = next.contextData?.template;
// function getRelativeUtilsPath(template: IProjectTemplate, isSingleComponent: boolean) {
// let relativeUtilsPath = '../../utils';
// const utilsPath = template.slots.utils.path;
// if (ir.containerType === 'Component') {
// // TODO: isSingleComponent
// relativeUtilsPath = getRelativePath(template.slots.components.path.join('/'), utilsPath.join('/'));
// }
// return relativeUtilsPath;
// }
next.chunks.push({ next.chunks.push({
type: ChunkType.STRING, type: ChunkType.STRING,
fileType: cfg.fileType, fileType: cfg.fileType,
@ -89,7 +103,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
type: ChunkType.STRING, type: ChunkType.STRING,
fileType: cfg.fileType, fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsMethod, name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
content: ` $ = () => null; `, content: ' $ = () => null; ',
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]], linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
}); });
@ -97,7 +111,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
type: ChunkType.STRING, type: ChunkType.STRING,
fileType: cfg.fileType, fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsMethod, name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
content: ` $$ = () => []; `, content: ' $$ = () => []; ',
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]], linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
}); });
} }

View File

@ -33,6 +33,14 @@ export interface IRouterInfo extends IWithDependency {
}>; }>;
} }
/**
* project's remarks
*/
export interface ProjectRemark {
/** if current project only contain one container which type is `Component` */
isSingleComponent?: boolean;
}
export interface IProjectInfo { export interface IProjectInfo {
css?: string; css?: string;
containersDeps?: IDependency[]; containersDeps?: IDependency[];
@ -43,6 +51,7 @@ export interface IProjectInfo {
meta?: { name?: string; title?: string } | Record<string, any>; meta?: { name?: string; title?: string } | Record<string, any>;
config?: Record<string, any>; config?: Record<string, any>;
dataSourcesTypes?: string[]; dataSourcesTypes?: string[];
projectRemark?: ProjectRemark;
} }
export interface IPageMeta { export interface IPageMeta {