UNPKG

@umijs/plugins

Version:
257 lines (255 loc) 9.49 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/locale.ts var locale_exports = {}; __export(locale_exports, { default: () => locale_default, packageNormalize: () => packageNormalize }); module.exports = __toCommonJS(locale_exports); var import_fs = require("fs"); var import_path = require("path"); var import_umi = require("umi"); var import_plugin_utils = require("umi/plugin-utils"); var import_localeUtils = require("./utils/localeUtils"); var import_withTmpPath = require("./utils/withTmpPath"); var packageNormalize = (packageName) => packageName.replace(/[@\/\-.]/g, "_"); var locale_default = (api) => { let hasAntd = false; try { hasAntd = !!require.resolve("antd"); } catch (e) { api.logger.warn("antd is not installed. <SelecLang /> unavailable"); } const defaultConfig = { baseNavigator: true, useLocalStorage: true, baseSeparator: "-", antd: hasAntd }; api.describe({ key: "locale", config: { schema({ zod }) { return zod.object({ default: zod.string(), useLocalStorage: zod.boolean(), baseNavigator: zod.boolean(), title: zod.boolean(), antd: zod.boolean(), baseSeparator: zod.string() }).partial(); } }, enableBy: api.EnableBy.config }); const reactIntlPkgPath = (0, import_plugin_utils.winPath)( (0, import_path.dirname)(require.resolve("react-intl/package")) ); api.addEntryImportsAhead( () => (0, import_localeUtils.isNeedPolyfill)(api.config.targets || {}) ? [ { source: require.resolve("intl") } ] : [] ); const addAntdLocales = async (args) => { var _a; return await api.applyPlugins({ key: "addAntdLocales", type: api.ApplyPluginsType.add, initialValue: [ `antd/${((_a = api.config) == null ? void 0 : _a.ssr) ? "lib" : "es"}/locale/${(0, import_localeUtils.getAntdLocale)( args.lang, args.country )}` ], args }); }; const getList = async (resolveKey) => { var _a; const { paths } = api; return (0, import_localeUtils.getLocaleList)({ localeFolder: "locales", separator: (_a = api.config.locale) == null ? void 0 : _a.baseSeparator, absSrcPath: paths.absSrcPath, absPagesPath: paths.absPagesPath, addAntdLocales, resolveKey }); }; api.onGenerateFiles(async () => { var _a, _b, _c, _d; const localeTpl = (0, import_fs.readFileSync)( (0, import_path.join)(__dirname, "../libs/locale/locale.tpl"), "utf-8" ); const resolveKey = api.config.moment2dayjs ? "dayjs" : "moment"; const momentPkgPath = (0, import_plugin_utils.winPath)( (0, import_path.dirname)(require.resolve(`${resolveKey}/package.json`)) ); const EventEmitterPkg = (0, import_plugin_utils.winPath)( (0, import_path.dirname)(require.resolve("event-emitter/package")) ); const { baseSeparator, baseNavigator, antd, title, useLocalStorage } = { ...defaultConfig, ...api.config.locale }; const defaultLocale = ((_a = api.config.locale) == null ? void 0 : _a.default) || `zh${baseSeparator}CN`; const localeList = await getList(resolveKey); const momentLocales = localeList.map(({ momentLocale }) => momentLocale).filter((locale) => locale); const antdLocales = localeList.map(({ antdLocale }) => antdLocale).filter((locale) => locale); let MomentLocales = momentLocales; let DefaultMomentLocale = ""; if (!MomentLocales.length && ((_b = api.config.locale) == null ? void 0 : _b.default)) { const [lang, country = ""] = defaultLocale.split(baseSeparator); const { momentLocale } = (0, import_localeUtils.getMomentLocale)(lang, country, resolveKey); if (momentLocale) { MomentLocales = [momentLocale]; DefaultMomentLocale = momentLocale; } } let DefaultAntdLocales = []; if (!antdLocales.length && ((_c = api.config.locale) == null ? void 0 : _c.antd)) { const [lang, country = ""] = defaultLocale.split(baseSeparator); DefaultAntdLocales = import_plugin_utils.lodash.uniq( await addAntdLocales({ lang, country }) ); } const NormalizeAntdLocalesName = function() { return packageNormalize(this); }; api.writeTmpFile({ content: import_plugin_utils.Mustache.render(localeTpl, { MomentLocales, DefaultMomentLocale, NormalizeAntdLocalesName, DefaultAntdLocales, Antd: !!antd, Title: title && api.config.title, BaseSeparator: baseSeparator, DefaultLocale: defaultLocale, DefaultLang: defaultLocale, momentPkgPath }), path: "locale.tsx" }); const localeExportsTpl = (0, import_fs.readFileSync)( (0, import_path.join)(__dirname, "../libs/locale/localeExports.tpl"), "utf-8" ); const localeDirName = "locales"; const localeDirPath = (0, import_path.join)(api.paths.absSrcPath, localeDirName); api.writeTmpFile({ path: "localeExports.ts", content: import_plugin_utils.Mustache.render(localeExportsTpl, { EventEmitterPkg, BaseSeparator: baseSeparator, BaseNavigator: baseNavigator, UseLocalStorage: !!useLocalStorage, LocaleDir: localeDirName, ExistLocaleDir: (0, import_fs.existsSync)(localeDirPath), LocaleList: localeList.map((locale) => ({ ...locale, antdLocale: locale.antdLocale.map((antdLocale, index) => ({ locale: antdLocale, index })), paths: locale.paths.map((path, index) => ({ path, index })) })), Antd: !!antd, DefaultLocale: JSON.stringify(defaultLocale), warningPkgPath: (0, import_plugin_utils.winPath)((0, import_path.dirname)(require.resolve("warning/package"))), reactIntlPkgPath }) }); const runtimeTpl = (0, import_fs.readFileSync)( (0, import_path.join)(__dirname, "../libs/locale/runtime.tpl"), "utf-8" ); api.writeTmpFile({ path: "runtime.tsx", content: import_plugin_utils.Mustache.render(runtimeTpl, { Title: !!title }) }); const selectLang = (0, import_fs.readFileSync)( (0, import_path.join)(__dirname, "../libs/locale/SelectLang.tpl"), "utf-8" ); api.writeTmpFile({ path: "SelectLang.tsx", content: import_plugin_utils.Mustache.render(selectLang, { Antd: !!antd, LocaleList: localeList, ShowSelectLang: localeList.length > 1 && !!antd, antdFiles: ((_d = api.config) == null ? void 0 : _d.ssr) ? "lib" : "es" }) }); api.writeTmpFile({ path: "index.ts", content: ` export { addLocale, setLocale, getLocale, getIntl, useIntl, injectIntl, formatMessage, FormattedMessage, getAllLocales, FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedHTMLMessage, FormattedList, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, IntlProvider, RawIntlProvider } from './localeExports'; export { SelectLang } from './SelectLang'; ` }); api.writeTmpFile({ path: import_umi.RUNTIME_TYPE_FILE_NAME, content: ` import { IntlCache, createIntl, } from '${reactIntlPkgPath}'; type OptionalIntlConfig = Omit<Parameters<typeof createIntl>[0], 'locale' | 'defaultLocale'>; export interface IRuntimeConfig { locale?: { getLocale?: () => string; cache?: IntlCache; } & OptionalIntlConfig; };` }); }); api.addRuntimePlugin(() => [(0, import_withTmpPath.withTmpPath)({ api, path: "runtime.tsx" })]); api.addRuntimePluginKey(() => ["locale"]); api.addTmpGenerateWatcherPaths(async () => { const resolveKey = api.config.moment2dayjs ? "dayjs" : "moment"; const localeList = await getList(resolveKey); return (0, import_localeUtils.exactLocalePaths)(localeList); }); }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { packageNormalize });