@umijs/plugins
Version:
302 lines (294 loc) • 9.22 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/dva.ts
var dva_exports = {};
__export(dva_exports, {
default: () => dva_default,
getAllModels: () => getAllModels,
getModelUtil: () => getModelUtil
});
module.exports = __toCommonJS(dva_exports);
var t = __toESM(require("@umijs/bundler-utils/compiled/babel/types"));
var import_utils = require("@umijs/utils");
var import_path = require("path");
var import_umi = require("umi");
var import_plugin_utils = require("umi/plugin-utils");
var import_modelUtils = require("./utils/modelUtils");
var import_withTmpPath = require("./utils/withTmpPath");
var dva_default = (api) => {
const pkgPath = (0, import_path.join)(__dirname, "../libs/dva.ts");
api.describe({
config: {
schema({ zod }) {
return zod.object({
extraModels: zod.array(zod.string()),
immer: zod.record(zod.any()),
skipModelValidate: zod.boolean()
}).deepPartial();
}
},
enableBy: api.EnableBy.config
});
api.modifyAppData((memo) => {
const models = getAllModels(api);
memo.pluginDva = {
pkgPath,
models
};
return memo;
});
api.modifyConfig((memo) => {
memo.alias["dva$"] = pkgPath;
return memo;
});
api.onGenerateFiles((args) => {
var _a, _b, _c, _d, _e, _f;
const models = args.isFirstTime ? api.appData.pluginDva.models : getAllModels(api);
api.writeTmpFile({
path: "models.ts",
content: import_modelUtils.ModelUtils.getModelsContent(models)
});
api.writeTmpFile({
path: import_umi.RUNTIME_TYPE_FILE_NAME,
content: `
export interface IRuntimeConfig {
dva?: {
config?: {
initialState?: Record<string, any>;
onError?: any;
onStateChange?: any;
onAction?: any;
onHmr?: any;
onReducer?: any;
onEffect?: any;
extraReducers?: any;
extraEnhancers?: any;
[key: string]: any;
},
plugins?: string[];
}
}
`
});
api.writeTmpFile({
path: "dva.tsx",
tpl: `
// It's faked dva
// aliased to @umijs/plugins/templates/dva
import { create, Provider } from 'dva';
import createLoading from '${(0, import_utils.winPath)(require.resolve("dva-loading"))}';
${((_a = api.config.dva) == null ? void 0 : _a.immer) ? `
import dvaImmer, { enableES5, enableAllPlugins } from '${(0, import_utils.winPath)(
require.resolve("dva-immer")
)}';
` : ""}
import React, { useRef } from 'react';
import { history, ApplyPluginsType, useAppData } from 'umi';
import { models } from './models';
let dvaApp: any;
export function RootContainer(props: any) {
const { pluginManager } = useAppData();
const app = useRef<any>();
const runtimeDva = pluginManager.applyPlugins({
key: 'dva',
type: ApplyPluginsType.modify,
initialValue: {},
});
if (!app.current) {
app.current = create(
{
history,
...(runtimeDva.config || {}),
},
{
initialReducer: {},
setupMiddlewares(middlewares: Function[]) {
return [...middlewares];
},
setupApp(app: IDvaApp) {
app._history = history;
},
},
);
dvaApp = app.current;
app.current.use(createLoading());
${((_b = api.config.dva) == null ? void 0 : _b.immer) ? `app.current.use(dvaImmer());` : ""}
${((_d = (_c = api.config.dva) == null ? void 0 : _c.immer) == null ? void 0 : _d.enableES5) ? `enableES5();` : ""}
${((_f = (_e = api.config.dva) == null ? void 0 : _e.immer) == null ? void 0 : _f.enableAllPlugins) ? `enableAllPlugins();` : ""}
(runtimeDva.plugins || []).forEach((p) => {
app.current.use(p);
});
for (const id of Object.keys(models)) {
app.current.model({
namespace: models[id].namespace,
...models[id].model,
});
}
app.current.start();
}
return <Provider store={app.current!._store}>{props.children}</Provider>;
}
export function getDvaApp() {
return dvaApp;
}
`,
context: {}
});
api.writeTmpFile({
path: "runtime.tsx",
content: `
import React from 'react';
import { RootContainer } from './dva';
export function dataflowProvider(container, opts) {
return React.createElement(RootContainer, opts, container);
}
`
});
api.writeTmpFile({
path: "index.ts",
content: `
export { connect, useDispatch, useStore, useSelector } from 'dva';
export { getDvaApp } from './dva';
`
});
api.writeTmpFile({
path: "types.d.ts",
tpl: `
import type { History } from 'umi';
export interface ConnectProps {
dispatch?: Dispatch;
}
type RequiredConnectProps = Required<ConnectProps>
export type ConnectRC<
T = {},
> = React.ForwardRefRenderFunction<any, T & RequiredConnectProps>;
interface Action<T = any> {
type: T
}
interface AnyAction extends Action {
// Allows any extra properties to be defined in an action.
[extraProps: string]: any
}
interface Dispatch<A extends Action = AnyAction> {
<T extends A>(action: T): T
}
interface EffectsCommandMap {
put: <A extends AnyAction>(action: A) => any,
call: Function,
select: Function,
take: Function,
cancel: Function,
[key: string]: any,
}
interface Action<T = any> {
type: T
}
export type Reducer<S = any, A extends Action = AnyAction> = (prevState: S, action: A) => S;
export type Effect = (action: AnyAction, effects: EffectsCommandMap) => void;
type EffectType = 'takeEvery' | 'takeLatest' | 'watcher' | 'throttle';
type EffectWithType = [Effect, { type: EffectType }];
export type Subscription = (api: SubscriptionAPI, done: Function) => void;
export interface ReducersMapObject<T> {
[key: string]: Reducer<T>,
}
export interface EffectsMapObject {
[key: string]: Effect | EffectWithType,
}
export interface SubscriptionAPI {
dispatch: Dispatch<any>,
history: History,
}
export interface SubscriptionsMapObject {
[key: string]: Subscription,
}
export interface DvaModel<T, E = EffectsMapObject, R = ReducersMapObject<T>> {
namespace: string,
state?: T,
reducers?: R,
effects?: E,
subscriptions?: SubscriptionsMapObject,
}
`,
context: {}
});
});
api.addTmpGenerateWatcherPaths(() => {
return [(0, import_path.join)(api.paths.absSrcPath, "models")];
});
api.addRuntimePlugin(() => {
return [(0, import_withTmpPath.withTmpPath)({ api, path: "runtime.tsx" })];
});
api.addRuntimePluginKey(() => ["dva"]);
api.registerCommand({
name: "dva",
fn() {
api.logger.info(import_plugin_utils.chalk.green.bold("dva models"));
api.appData.pluginDva.models.forEach((model) => {
api.logger.info(` - ${(0, import_path.relative)(api.cwd, model.file)}`);
});
}
});
};
function getModelUtil(api) {
return new import_modelUtils.ModelUtils(api, {
contentTest(content) {
if (api == null ? void 0 : api.config.dva.skipModelValidate)
return true;
return content.startsWith("// @dva-model");
},
astTest({ node, content }) {
if (isModelObject(node)) {
return true;
} else if (content.includes("dva-model-extend") && t.isCallExpression(node) && node.arguments.length === 2 && isModelObject(node.arguments[1])) {
return true;
}
return false;
}
});
}
function getAllModels(api) {
return getModelUtil(api).getAllModels({
extraModels: [...api.config.dva.extraModels || []]
});
}
function isModelObject(node) {
return t.isObjectExpression(node) && node.properties.some((property) => {
return [
"state",
"reducers",
"subscriptions",
"effects",
"namespace"
].includes(property.key.name);
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getAllModels,
getModelUtil
});