UNPKG

@umijs/plugins

Version:
386 lines (381 loc) 14.6 kB
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/antd.ts var antd_exports = {}; __export(antd_exports, { default: () => antd_default }); module.exports = __toCommonJS(antd_exports); var import_moment_webpack_plugin = __toESM(require("@ant-design/moment-webpack-plugin")); var import_assert = __toESM(require("assert")); var import_path = require("path"); var import_umi = require("umi"); var import_plugin_utils = require("umi/plugin-utils"); var import_constants = require("./constants"); var import_resolveProjectDep = require("./utils/resolveProjectDep"); var import_withTmpPath = require("./utils/withTmpPath"); var ANTD_TEMPLATES_DIR = (0, import_path.join)(import_constants.TEMPLATES_DIR, "antd"); var antd_default = (api) => { let pkgPath; let antdVersion = "4.0.0"; try { pkgPath = (0, import_resolveProjectDep.resolveProjectDep)({ pkg: api.pkg, cwd: api.cwd, dep: "antd" }) || (0, import_path.dirname)(require.resolve("antd/package.json")); antdVersion = require(`${pkgPath}/package.json`).version; } catch (e) { } const isModern = import_plugin_utils.semver.satisfies( antdVersion, "^5.0.0 || ^6.0.0", // 两者都还在维护周期中,允许使用预发布版本. eg. 6.1.0-alpha.0 { includePrerelease: true } ); const isLegacy = import_plugin_utils.semver.satisfies(antdVersion, "^4.0.0"); const appComponentAvailable = import_plugin_utils.semver.gte(antdVersion, "5.1.0"); const appConfigAvailable = import_plugin_utils.semver.gte(antdVersion, "5.3.0"); const day2MomentAvailable = import_plugin_utils.semver.gte(antdVersion, "5.0.0"); api.describe({ config: { schema({ zod }) { const commonSchema = { dark: zod.boolean(), compact: zod.boolean(), // babel-plugin-import import: zod.boolean(), // less or css, default less style: zod.enum(["less", "css"]).describe("less or css, default less") }; const createZodRecordWithSpecifiedPartial = (partial) => { const keys = Object.keys(partial); return zod.union([ zod.object(partial), zod.record(zod.any()).refine((obj) => { return !keys.some((key) => key in obj); }) ]); }; const createModernSchema = () => { const componentNameSchema = zod.string().refine( (value) => { const firstLetter = value.slice(0, 1); return firstLetter === firstLetter.toUpperCase(); }, { message: "theme.components.[componentName] needs to be in PascalCase, e.g. theme.components.Button" } ); const themeSchema = createZodRecordWithSpecifiedPartial({ components: zod.record(componentNameSchema, zod.record(zod.any())) }); const configProvider = createZodRecordWithSpecifiedPartial({ theme: themeSchema }); return zod.object({ ...commonSchema, theme: themeSchema.describe("Shortcut of `configProvider.theme`"), appConfig: zod.record(zod.any()).describe("Only >= antd@5.1.0 is supported"), momentPicker: zod.boolean().describe("DatePicker & Calendar use moment version"), styleProvider: zod.record(zod.any()), configProvider }).deepPartial(); }; const createLegacySchema = () => { return zod.object({ ...commonSchema, configProvider: zod.record(zod.any()) }).deepPartial(); }; if (isModern) { return createModernSchema(); } if (isLegacy) { return createLegacySchema(); } return zod.object({}); } }, enableBy({ userConfig }) { return process.env.UMI_PLUGIN_ANTD_ENABLE || userConfig.antd; } }); api.addRuntimePluginKey(() => ["antd"]); function checkPkgPath() { if (!pkgPath) { throw new Error(`Can't find antd package. Please install antd first.`); } } api.onCheck(() => { if (import_plugin_utils.semver.gte(antdVersion, "6.0.0")) { const reactVersion = api.appData.react.version; if (import_plugin_utils.semver.lt(reactVersion, "18.0.0")) { throw new Error( `antd@6 requires React version >= 18.0.0, but got ${reactVersion}.` ); } } }); api.modifyAppData((memo) => { checkPkgPath(); const version = require(`${pkgPath}/package.json`).version; memo.antd = { pkgPath, version }; return memo; }); api.modifyConfig((memo) => { var _a; checkPkgPath(); let antd = memo.antd || {}; if (process.env.UMI_PLUGIN_ANTD_ENABLE) { const { defaultConfig } = JSON.parse(process.env.UMI_PLUGIN_ANTD_ENABLE); memo.antd = antd = Object.assign(defaultConfig, antd); } memo.alias.antd = pkgPath; if (isModern) { const theme = require("@ant-design/antd-theme-variable"); memo.theme = { ...theme, ...memo.theme }; } if (import_plugin_utils.semver.gte(antdVersion, "5.0.0")) { if ((_a = memo.antd) == null ? void 0 : _a.import) { const errorMessage = `The antd.import option is not supported in antd version 5 and above (${antdVersion}).`; api.logger.fatal( "please change config antd.import to false, then start server again" ); throw Error(errorMessage); } } if (isLegacy) { if (antd.dark || antd.compact) { const { getThemeVariables } = require("antd/dist/theme"); memo.theme = { ...getThemeVariables(antd), ...memo.theme }; } memo.theme = { "root-entry-name": "default", ...memo.theme }; } if (antd.theme) { (0, import_assert.default)( isModern, `The 'antd.theme' option is only available for antd version 5 and above.` ); antd.configProvider ?? (antd.configProvider = {}); antd.configProvider.theme = (0, import_plugin_utils.deepmerge)( antd.configProvider.theme || {}, antd.theme ); (0, import_assert.default)( !antd.configProvider.theme.algorithm, `The 'algorithm' option only available for runtime config, please move it to the runtime plugin, see: https://umijs.org/docs/max/antd#运行时配置` ); } if (antd.appConfig) { if (!appComponentAvailable) { delete antd.appConfig; api.logger.warn( `antd.appConfig is only available in version 5.1.0 and above, but you are using version ${antdVersion}` ); } else if (!appConfigAvailable && Object.keys(antd.appConfig).length > 0) { api.logger.warn( `versions [5.1.0 ~ 5.3.0) only allows antd.appConfig to be set to \`{}\`` ); } } if (antd.dark || antd.compact) { antd.configProvider ?? (antd.configProvider = {}); } return memo; }); api.chainWebpack((memo) => { if (api.config.antd.momentPicker) { if (day2MomentAvailable) { memo.plugin("antd-moment-webpack-plugin").use(import_moment_webpack_plugin.default); } else { api.logger.warn( `MomentPicker is only available in version 5.0.0 and above, but you are using version ${antdVersion}` ); } } return memo; }); api.addExtraBabelPlugins(() => { const style = api.config.antd.style || "less"; if (api.config.antd.import && !api.appData.vite) { return [ [ require.resolve("babel-plugin-import"), { libraryName: "antd", libraryDirectory: "es", style: style === "less" || "css" }, "antd" ] ]; } return []; }); const lodashPkg = (0, import_path.dirname)(require.resolve("lodash/package.json")); const lodashPath = { merge: (0, import_plugin_utils.winPath)((0, import_path.join)(lodashPkg, "merge")) }; api.onGenerateFiles(() => { var _a; const withConfigProvider = !!api.config.antd.configProvider; const withAppConfig = appConfigAvailable && !!api.config.antd.appConfig; const styleProvider = api.config.antd.styleProvider; const userInputCompact = api.config.antd.compact; const userInputDark = api.config.antd.dark; const ieTarget = !!((_a = api.config.targets) == null ? void 0 : _a.ie) || !!api.config.legacy; let styleProviderConfig = false; if (isModern && (ieTarget || styleProvider)) { const cssinjs = (0, import_resolveProjectDep.resolveProjectDep)({ pkg: api.pkg, cwd: api.cwd, dep: "@ant-design/cssinjs" }) || (0, import_path.dirname)(require.resolve("@ant-design/cssinjs/package.json")); if (cssinjs) { styleProviderConfig = { cssinjs: (0, import_plugin_utils.winPath)(cssinjs) }; if (ieTarget) { if (import_plugin_utils.semver.gte(antdVersion, "6.0.0")) { api.logger.warn( `You are using antd version ${antdVersion} which no longer supports IE, but your targets or legacy config indicates IE support. Please adjust your targets or legacy config accordingly.` ); } else { styleProviderConfig.hashPriority = "high"; styleProviderConfig.legacyTransformer = true; } } styleProviderConfig = { ...styleProviderConfig, ...styleProvider }; } } const configProvider = withConfigProvider && JSON.stringify(api.config.antd.configProvider); const appConfig = appComponentAvailable && JSON.stringify(api.config.antd.appConfig); const enableModernThemeAlgorithm = isModern && (userInputCompact || userInputDark) ? { compact: userInputCompact, dark: userInputDark } : false; const hasConfigProvider = configProvider || enableModernThemeAlgorithm; const antdConfigSetter = isModern && hasConfigProvider; const isModelPluginEnabled = api.isPluginEnable("model"); const modelPluginCompat = isModelPluginEnabled && antdConfigSetter; api.writeTmpFile({ path: `runtime.tsx`, context: { configProvider, appConfig, styleProvider: styleProviderConfig, // 是否启用了 theme algorithm enableModernThemeAlgorithm, antdConfigSetter, modelPluginCompat, lodashPath, /** * 是否重构了全局静态配置。 重构后需要在运行时将全局静态配置传入到 ConfigProvider 中。 * 实际上 4.13.0 重构后有一个 bug,真正的 warn 出现在 4.13.1,并且 4.13.1 修复了这个 bug。 * Resolve issue: https://github.com/umijs/umi/issues/10231 * `InternalStatic` 指 `Modal.config` 等静态方法,详见:https://github.com/ant-design/ant-design/pull/29285 */ disableInternalStatic: import_plugin_utils.semver.gt(antdVersion, "4.13.0") }, tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(ANTD_TEMPLATES_DIR, "runtime.ts.tpl")) }); api.writeTmpFile({ path: "types.d.ts", context: { withConfigProvider, withAppConfig }, tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(ANTD_TEMPLATES_DIR, "types.d.ts.tpl")) }); api.writeTmpFile({ path: import_umi.RUNTIME_TYPE_FILE_NAME, content: ` import type { RuntimeAntdConfig } from './types.d'; export type IRuntimeConfig = { antd?: RuntimeAntdConfig }; ` }); if (antdConfigSetter) { api.writeTmpFile({ path: "index.tsx", content: `import React from 'react'; import { AntdConfigContext, AntdConfigContextSetter } from './context'; export function useAntdConfig() { return React.useContext(AntdConfigContext); } export function useAntdConfigSetter() { return React.useContext(AntdConfigContextSetter); }` }); api.writeTmpFile({ path: "context.tsx", content: `import React from 'react'; import type { ConfigProviderProps } from 'antd/es/config-provider'; export const AntdConfigContext = React.createContext<ConfigProviderProps>(null!); export const AntdConfigContextSetter = React.createContext<React.Dispatch<React.SetStateAction<ConfigProviderProps>>>( () => { console.error(\`The 'useAntdConfigSetter()' method depends on the antd 'ConfigProvider', requires one of 'antd.configProvider' / 'antd.dark' / 'antd.compact' to be enabled.\`); } ); ` }); } }); api.addRuntimePlugin(() => { if (api.config.antd.styleProvider || api.config.antd.configProvider || appComponentAvailable && api.config.antd.appConfig) { return [(0, import_withTmpPath.withTmpPath)({ api, path: "runtime.tsx" })]; } return []; }); api.addEntryImportsAhead(() => { const style = api.config.antd.style || "less"; const imports = []; if (isModern) { imports.push({ source: "antd/dist/reset.css" }); } else if (!api.config.antd.import || api.appData.vite) { imports.push({ source: style === "less" ? "antd/dist/antd.less" : "antd/dist/antd.css" }); } return imports; }); };