@ali-i18n-fe/dada-component
Version:
108 lines (90 loc) • 2.74 kB
JavaScript
const path = require("path");
const fs = require("fs");
const { wrapJsDom } = require("./wrapWindow");
const { getDocsRender } = require("./getDocsRender");
/**
* 根据Docs创建Dada JSON
* @param webpackConfig
* @returns {*}
*/
function buildDadaSchema(webpackConfig) {
const { path: output } = webpackConfig.output;
const routeMap =
webpackConfig.routeMap || require(path.resolve(output, "routeMap.json"));
const dadaDemos = {};
Object.entries(routeMap).forEach(([docsPath, uiType]) => {
const mockComponent = (props) => {
const { children, itemData, ...restProps } = props;
// TODO :: renderComponent -> children
const schema = {
uiType,
...restProps,
};
dadaDemos[uiType] = schema;
};
const docsRenders = wrapJsDom(
require,
mockReactDom
)(path.resolve(output, docsPath));
const docsRender = getDocsRender(docsRenders);
wrapJsDom(docsRender, mockReactDom)(mockComponent, {});
});
const writeFile = path.resolve(webpackConfig.output.path, "dadaSchema.json");
fs.writeFileSync(writeFile, JSON.stringify(dadaDemos), "utf8");
console.log(`Dada Demo Schema生成成功: ${writeFile}`.green);
return dadaDemos;
}
const fn = (value) => {
if (value === undefined) {
return {};
}
return value;
};
const MockDispatcher = {
readContext: fn,
useContext: fn,
useMemo: fn,
useReducer: fn,
useRef: fn,
useState: (defaultValue) => [defaultValue, (value) => value],
useLayoutEffect: fn,
useCallback: fn,
// useImperativeHandle is not run in the server environment
useImperativeHandle: fn,
// Effects are not run in the server environment.
useEffect: fn,
// Debugging effect
useDebugValue: fn,
useResponder: fn,
useDeferredValue: fn,
useTransition: fn,
};
const mockReactDom = {
render(element) {
const React = require(path.resolve(
process.cwd(),
"node_modules",
"react/index.js"
));
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current = MockDispatcher;
const { type, props = {} } = element;
let { children = [] } = props;
if (typeof type === "function") {
let elements = null;
if (type.prototype instanceof React.Component) {
elements = new type(props).render();
} else {
elements = type(props);
}
try {
elements && this.render(elements);
} catch (e) {}
}
children = Array.isArray(children) ? children : [children];
children.forEach((child) => {
this.render(child);
});
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher.current = null;
},
};
exports.buildDadaSchema = buildDadaSchema;