refactor: 优化 resolver inner dep and declare type file

This commit is contained in:
winixt 2022-03-28 21:03:13 +08:00
parent 0816e25905
commit 97b9e8fa3c
17 changed files with 177 additions and 196 deletions

View File

@ -9,18 +9,12 @@ import { AsyncSeriesWaterfallHook } from 'tapable';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { lodash, chalk } from '@fesjs/utils'; import { lodash, chalk } from '@fesjs/utils';
import { Command, Option } from 'commander'; import { Command, Option } from 'commander';
import { resolvePresets, pathToObj, resolvePlugins } from './utils/pluginUtils'; import { resolvePresets, filterBuilder, pathToObj, resolvePlugins } from './utils/pluginUtils';
import loadDotEnv from './utils/loadDotEnv'; import loadDotEnv from './utils/loadDotEnv';
import isPromise from './utils/isPromise'; import isPromise from './utils/isPromise';
import BabelRegister from './babelRegister'; import BabelRegister from './babelRegister';
import PluginAPI from './pluginAPI'; import PluginAPI from './pluginAPI';
import { import { ApplyPluginsType, ConfigChangeType, EnableBy, PluginType, ServiceStage } from './enums';
ApplyPluginsType,
ConfigChangeType,
EnableBy,
PluginType,
ServiceStage
} from './enums';
import Config from '../config'; import Config from '../config';
import { getUserConfigWithKey } from '../config/utils/configUtils'; import { getUserConfigWithKey } from '../config/utils/configUtils';
import getPaths from './getPaths'; import getPaths from './getPaths';
@ -95,6 +89,11 @@ export default class Service extends EventEmitter {
this.env = opts.env || process.env.NODE_ENV; this.env = opts.env || process.env.NODE_ENV;
this.fesPkg = opts.fesPkg || {}; this.fesPkg = opts.fesPkg || {};
const builderPkgPath = filterBuilder(this.pkg);
this.builder = {
isVite: (builderPkgPath[0] || '').includes('build-vite'),
innerDepPrefix: '@fesInner',
};
assert(existsSync(this.cwd), `cwd ${this.cwd} does not exist.`); assert(existsSync(this.cwd), `cwd ${this.cwd} does not exist.`);
@ -108,7 +107,7 @@ export default class Service extends EventEmitter {
this.configInstance = new Config({ this.configInstance = new Config({
cwd: this.cwd, cwd: this.cwd,
service: this, service: this,
localConfig: this.env === 'development' localConfig: this.env === 'development',
}); });
this.userConfig = this.configInstance.getUserConfig(); this.userConfig = this.configInstance.getUserConfig();
@ -116,26 +115,25 @@ export default class Service extends EventEmitter {
this.paths = getPaths({ this.paths = getPaths({
cwd: this.cwd, cwd: this.cwd,
config: this.userConfig, config: this.userConfig,
env: this.env env: this.env,
}); });
this.program = this.initCommand(); this.program = this.initCommand();
// setup initial plugins // setup initial plugins
const baseOpts = { const baseOpts = {
pkg: this.pkg, pkg: this.pkg,
cwd: this.cwd cwd: this.cwd,
}; };
this.initialPresets = resolvePresets({ this.initialPresets = resolvePresets({
...baseOpts, ...baseOpts,
presets: opts.presets || [], presets: opts.presets || [],
userConfigPresets: this.userConfig.presets || [] userConfigPresets: this.userConfig.presets || [],
}); });
this.initialPlugins = resolvePlugins({ this.initialPlugins = resolvePlugins({
...baseOpts, ...baseOpts,
plugins: opts.plugins || [], plugins: opts.plugins || [],
userConfigPlugins: this.userConfig.plugins || [] userConfigPlugins: this.userConfig.plugins || [],
}); });
} }
@ -182,7 +180,7 @@ export default class Service extends EventEmitter {
this.setStage(ServiceStage.pluginReady); this.setStage(ServiceStage.pluginReady);
await this.applyPlugins({ await this.applyPlugins({
key: 'onPluginReady', key: 'onPluginReady',
type: ApplyPluginsType.event type: ApplyPluginsType.event,
}); });
// get config, including: // get config, including:
@ -200,7 +198,7 @@ export default class Service extends EventEmitter {
const paths = await this.applyPlugins({ const paths = await this.applyPlugins({
key: 'modifyPaths', key: 'modifyPaths',
type: ApplyPluginsType.modify, type: ApplyPluginsType.modify,
initialValue: this.paths initialValue: this.paths,
}); });
Object.keys(paths).forEach((key) => { Object.keys(paths).forEach((key) => {
this.paths[key] = paths[key]; this.paths[key] = paths[key];
@ -211,14 +209,14 @@ export default class Service extends EventEmitter {
const defaultConfig = await this.applyPlugins({ const defaultConfig = await this.applyPlugins({
key: 'modifyDefaultConfig', key: 'modifyDefaultConfig',
type: this.ApplyPluginsType.modify, type: this.ApplyPluginsType.modify,
initialValue: await this.configInstance.getDefaultConfig() initialValue: await this.configInstance.getDefaultConfig(),
}); });
this.config = await this.applyPlugins({ this.config = await this.applyPlugins({
key: 'modifyConfig', key: 'modifyConfig',
type: this.ApplyPluginsType.modify, type: this.ApplyPluginsType.modify,
initialValue: this.configInstance.getConfig({ initialValue: this.configInstance.getConfig({
defaultConfig defaultConfig,
}) }),
}); });
} }
@ -242,16 +240,10 @@ export default class Service extends EventEmitter {
const pluginAPI = new PluginAPI(opts); const pluginAPI = new PluginAPI(opts);
// register built-in methods // register built-in methods
[ ['onPluginReady', 'modifyPaths', 'onStart', 'modifyDefaultConfig', 'modifyConfig'].forEach((name) => {
'onPluginReady',
'modifyPaths',
'onStart',
'modifyDefaultConfig',
'modifyConfig'
].forEach((name) => {
pluginAPI.registerMethod({ pluginAPI.registerMethod({
name, name,
exitsError: false exitsError: false,
}); });
}); });
@ -279,15 +271,14 @@ export default class Service extends EventEmitter {
'args', 'args',
'hasPlugins', 'hasPlugins',
'hasPresets', 'hasPresets',
'setConfig' 'setConfig',
'builder',
].includes(prop) ].includes(prop)
) { ) {
return typeof this[prop] === 'function' return typeof this[prop] === 'function' ? this[prop].bind(this) : this[prop];
? this[prop].bind(this)
: this[prop];
} }
return target[prop]; return target[prop];
} },
}); });
} }
@ -309,24 +300,23 @@ export default class Service extends EventEmitter {
this.registerPlugin(preset); this.registerPlugin(preset);
const { presets, plugins } = await this.applyAPI({ const { presets, plugins } = await this.applyAPI({
api, api,
apply apply,
}); });
// register extra presets and plugins // register extra presets and plugins
if (presets) { if (presets) {
assert( assert(Array.isArray(presets), `presets returned from preset ${id} must be Array.`);
Array.isArray(presets),
`presets returned from preset ${id} must be Array.`
);
// 插到最前面,下个 while 循环优先执行 // 插到最前面,下个 while 循环优先执行
this._extraPresets.splice( this._extraPresets.splice(
0, 0,
0, 0,
...presets.map(path => pathToObj({ ...presets.map((path) =>
pathToObj({
type: PluginType.preset, type: PluginType.preset,
path, path,
cwd: this.cwd cwd: this.cwd,
})) }),
),
); );
} }
@ -339,42 +329,40 @@ export default class Service extends EventEmitter {
} }
if (plugins) { if (plugins) {
assert( assert(Array.isArray(plugins), `plugins returned from preset ${id} must be Array.`);
Array.isArray(plugins),
`plugins returned from preset ${id} must be Array.`
);
this._extraPlugins.push( this._extraPlugins.push(
...plugins.map(path => pathToObj({ ...plugins.map((path) =>
pathToObj({
type: PluginType.plugin, type: PluginType.plugin,
path, path,
cwd: this.cwd cwd: this.cwd,
})) }),
),
); );
} }
} }
async initPlugin(plugin) { async initPlugin(plugin) {
const { id, key, apply } = plugin; const { id, key, apply } = plugin;
const api = this.getPluginAPI({ const api = this.getPluginAPI({
id, id,
key, key,
service: this service: this,
}); });
// register before apply // register before apply
this.registerPlugin(plugin); this.registerPlugin(plugin);
await this.applyAPI({ await this.applyAPI({
api, api,
apply apply,
}); });
} }
getPluginOptsWithKey(key) { getPluginOptsWithKey(key) {
return getUserConfigWithKey({ return getUserConfigWithKey({
key, key,
userConfig: this.userConfig userConfig: this.userConfig,
}); });
} }
@ -424,10 +412,7 @@ export default class Service extends EventEmitter {
switch (opts.type) { switch (opts.type) {
case ApplyPluginsType.add: case ApplyPluginsType.add:
if ('initialValue' in opts) { if ('initialValue' in opts) {
assert( assert(Array.isArray(opts.initialValue), 'applyPlugins failed, opts.initialValue must be Array if opts.type is add.');
Array.isArray(opts.initialValue),
'applyPlugins failed, opts.initialValue must be Array if opts.type is add.'
);
} }
// eslint-disable-next-line // eslint-disable-next-line
const tAdd = new AsyncSeriesWaterfallHook(["memo"]); const tAdd = new AsyncSeriesWaterfallHook(["memo"]);
@ -440,12 +425,12 @@ export default class Service extends EventEmitter {
name: hook.pluginId, name: hook.pluginId,
stage: hook.stage || 0, stage: hook.stage || 0,
// @ts-ignore // @ts-ignore
before: hook.before before: hook.before,
}, },
async (memo) => { async (memo) => {
const items = await hook.fn(opts.args); const items = await hook.fn(opts.args);
return memo.concat(items); return memo.concat(items);
} },
); );
} }
return tAdd.promise(opts.initialValue || []); return tAdd.promise(opts.initialValue || []);
@ -461,9 +446,9 @@ export default class Service extends EventEmitter {
name: hook.pluginId, name: hook.pluginId,
stage: hook.stage || 0, stage: hook.stage || 0,
// @ts-ignore // @ts-ignore
before: hook.before before: hook.before,
}, },
async memo => hook.fn(memo, opts.args) async (memo) => hook.fn(memo, opts.args),
); );
} }
return tModify.promise(opts.initialValue); return tModify.promise(opts.initialValue);
@ -479,18 +464,16 @@ export default class Service extends EventEmitter {
name: hook.pluginId, name: hook.pluginId,
stage: hook.stage || 0, stage: hook.stage || 0,
// @ts-ignore // @ts-ignore
before: hook.before before: hook.before,
}, },
async () => { async () => {
await hook.fn(opts.args); await hook.fn(opts.args);
} },
); );
} }
return tEvent.promise(); return tEvent.promise();
default: default:
throw new Error( throw new Error(`applyPlugin failed, type is not defined or is not matched, got ${opts.type}.`);
`applyPlugin failed, type is not defined or is not matched, got ${opts.type}.`
);
} }
} }
@ -511,8 +494,8 @@ export default class Service extends EventEmitter {
key: 'onStart', key: 'onStart',
type: ApplyPluginsType.event, type: ApplyPluginsType.event,
args: { args: {
args args,
} },
}); });
return this.runCommand({ rawArgv, args }); return this.runCommand({ rawArgv, args });
@ -539,7 +522,10 @@ export default class Service extends EventEmitter {
if (commandOptionConfig.fn) { if (commandOptionConfig.fn) {
c.action(async () => { c.action(async () => {
await commandOptionConfig.fn({ await commandOptionConfig.fn({
rawArgv, args, options: c.opts(), program rawArgv,
args,
options: c.opts(),
program,
}); });
}); });
} }
@ -551,14 +537,10 @@ export default class Service extends EventEmitter {
async parseCommand() { async parseCommand() {
this.program.on('--help', () => { this.program.on('--help', () => {
console.log(); console.log();
console.log( console.log(` Run ${chalk.cyan('fes <command> --help')} for detailed usage of given command.`);
` Run ${chalk.cyan(
'fes <command> --help'
)} for detailed usage of given command.`
);
console.log(); console.log();
}); });
this.program.commands.forEach(c => c.on('--help', () => console.log())); this.program.commands.forEach((c) => c.on('--help', () => console.log()));
return this.program.parseAsync(process.argv); return this.program.parseAsync(process.argv);
} }
} }

View File

@ -26,7 +26,7 @@ function filterPluginAndPreset(type, pkg) {
.filter(isPluginOrPreset.bind(null, type)); .filter(isPluginOrPreset.bind(null, type));
} }
function filterBuilder(pkg) { export function filterBuilder(pkg) {
const builders = Object.keys(pkg.devDependencies || {}) const builders = Object.keys(pkg.devDependencies || {})
.concat(Object.keys(pkg.dependencies || {})) .concat(Object.keys(pkg.dependencies || {}))
.filter((name) => /^@fesjs\/build-/.test(name)); .filter((name) => /^@fesjs\/build-/.test(name));

View File

@ -1,6 +1,7 @@
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { resolvePkg } from '@fesjs/utils'; import { resolveInnerDep } from '@fesjs/utils';
import { name } from '../package.json';
const namespace = 'plugin-access'; const namespace = 'plugin-access';
@ -32,7 +33,7 @@ export default (api) => {
path: absoluteFilePath, path: absoluteFilePath,
content: Mustache.render(readFileSync(join(__dirname, 'runtime/core.tpl'), 'utf-8'), { content: Mustache.render(readFileSync(join(__dirname, 'runtime/core.tpl'), 'utf-8'), {
REPLACE_ROLES: JSON.stringify(roles), REPLACE_ROLES: JSON.stringify(roles),
lodashPath: resolvePkg('lodash-es'), lodashPath: resolveInnerDep('lodash-es', api.builder),
}), }),
}); });
@ -53,4 +54,10 @@ export default (api) => {
api.addRuntimePluginKey(() => 'access'); api.addRuntimePluginKey(() => 'access');
api.addRuntimePlugin(() => `@@/${absRuntimeFilePath}`); api.addRuntimePlugin(() => `@@/${absRuntimeFilePath}`);
api.addConfigType(() => ({
source: name,
runtime: ['AccessRuntimeConfig'],
build: ['AccessBuildConfig'],
}));
}; };

View File

@ -1,6 +1,7 @@
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { winPath } from '@fesjs/utils'; import { winPath } from '@fesjs/utils';
import { name } from '../package.json';
const namespace = 'plugin-layout'; const namespace = 'plugin-layout';
@ -28,13 +29,11 @@ export default (api) => {
const absRuntimeFilePath = join(namespace, 'runtime.js'); const absRuntimeFilePath = join(namespace, 'runtime.js');
api.onGenerateFiles(async () => { api.onGenerateFiles(async () => {
const { name } = api.pkg;
const HAS_LOCALE = api.hasPlugins(['@fesjs/plugin-locale']); const HAS_LOCALE = api.hasPlugins(['@fesjs/plugin-locale']);
// .fes配置 // .fes配置
const userConfig = { const userConfig = {
title: name, title: api.pkg.name,
footer: 'Created by Fes.js', footer: 'Created by Fes.js',
...(api.config.layout || {}), ...(api.config.layout || {}),
}; };
@ -81,4 +80,10 @@ export default (api) => {
children: routes, children: routes,
}, },
]); ]);
api.addConfigType(() => ({
source: name,
runtime: ['LayoutRuntimeConfig'],
build: ['LayoutBuildConfig'],
}));
}; };

View File

@ -1,7 +1,8 @@
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { resolvePkg } from '@fesjs/utils'; import { resolveInnerDep } from '@fesjs/utils';
import { getLocalesJSON } from './utils'; import { getLocalesJSON } from './utils';
import { name } from '../package.json';
const namespace = 'plugin-locale'; const namespace = 'plugin-locale';
@ -62,7 +63,7 @@ export default (api) => {
2, 2,
), ),
BASE_NAVIGATOR: userConfig.baseNavigator, BASE_NAVIGATOR: userConfig.baseNavigator,
VUE_I18N_PATH: resolvePkg('vue-i18n'), VUE_I18N_PATH: resolveInnerDep('vue-i18n', api.builder),
}), }),
}); });
@ -81,4 +82,9 @@ export default (api) => {
]); ]);
api.addRuntimePlugin(() => `@@/${absRuntimeFilePath}`); api.addRuntimePlugin(() => `@@/${absRuntimeFilePath}`);
api.addConfigType(() => ({
source: name,
build: ['LocalBuildConfig'],
}));
}; };

View File

@ -1,6 +1,7 @@
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { resolvePkg } from '@fesjs/utils'; import { resolveInnerDep } from '@fesjs/utils';
import { name } from '../package.json';
const namespace = 'plugin-monaco-editor'; const namespace = 'plugin-monaco-editor';
@ -47,14 +48,14 @@ export default (api) => {
api.writeTmpFile({ api.writeTmpFile({
path: absLoaderFilePath, path: absLoaderFilePath,
content: Mustache.render(readFileSync(join(__dirname, 'runtime/loader.tpl'), 'utf-8'), { content: Mustache.render(readFileSync(join(__dirname, 'runtime/loader.tpl'), 'utf-8'), {
MONACO_EDITOR: resolvePkg('monaco-editor'), MONACO_EDITOR: resolveInnerDep('monaco-editor', api.builder),
}), }),
}); });
api.writeTmpFile({ api.writeTmpFile({
path: absEditorFilePath, path: absEditorFilePath,
content: Mustache.render(readFileSync(join(__dirname, 'runtime/editor.tpl'), 'utf-8'), { content: Mustache.render(readFileSync(join(__dirname, 'runtime/editor.tpl'), 'utf-8'), {
LODASH_ES: resolvePkg('lodash-es'), LODASH_ES: resolveInnerDep('lodash-es', api.builder),
}), }),
}); });
@ -80,4 +81,9 @@ export default (api) => {
webpackConfig.plugin('monaco-editor').use(require('monaco-editor-webpack-plugin'), [api.config?.monacoEditor || {}]); webpackConfig.plugin('monaco-editor').use(require('monaco-editor-webpack-plugin'), [api.config?.monacoEditor || {}]);
return webpackConfig; return webpackConfig;
}); });
api.addConfigType(() => ({
source: name,
build: ['MonacoEditorBuildConfig'],
}));
}; };

View File

@ -1,34 +1,27 @@
import { readFileSync, existsSync } from 'fs'; import { readFileSync, existsSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { resolvePkg } from '@fesjs/utils'; import { resolveInnerDep } from '@fesjs/utils';
import { import { defaultMainRootId, defaultHistoryType, qiankunStateForMicroModelNamespace } from '../constants';
defaultMainRootId,
defaultHistoryType,
qiankunStateForMicroModelNamespace
} from '../constants';
import modifyRoutes from './modifyRoutes'; import modifyRoutes from './modifyRoutes';
const namespace = 'plugin-qiankun/main'; const namespace = 'plugin-qiankun/main';
export function isMasterEnable(api) { export function isMasterEnable(api) {
return ( return !!api.userConfig?.qiankun?.main || !!process.env.INITIAL_QIANKUN_MAIN_OPTIONS;
!!api.userConfig?.qiankun?.main
|| !!process.env.INITIAL_QIANKUN_MAIN_OPTIONS
);
} }
export default function (api) { export default function (api) {
const { const {
utils: { Mustache, winPath } utils: { Mustache, winPath },
} = api; } = api;
api.describe({ api.describe({
enableBy: () => isMasterEnable(api) enableBy: () => isMasterEnable(api),
}); });
api.modifyDefaultConfig(config => ({ api.modifyDefaultConfig((config) => ({
...config, ...config,
mountElementId: defaultMainRootId mountElementId: defaultMainRootId,
})); }));
modifyRoutes({ api, namespace }); modifyRoutes({ api, namespace });
@ -37,58 +30,33 @@ export default function (api) {
const absMicroAppWithMemoHistoryPath = join(namespace, 'MicroAppWithMemoHistory.js'); const absMicroAppWithMemoHistoryPath = join(namespace, 'MicroAppWithMemoHistory.js');
const absRuntimePath = join(namespace, 'runtime.js'); const absRuntimePath = join(namespace, 'runtime.js');
const absMasterOptionsPath = join(namespace, 'masterOptions.js'); const absMasterOptionsPath = join(namespace, 'masterOptions.js');
const absGetMicroAppRouteCompPath = join( const absGetMicroAppRouteCompPath = join(namespace, 'getMicroAppRouteComponent.js');
namespace,
'getMicroAppRouteComponent.js'
);
api.onGenerateFiles(() => { api.onGenerateFiles(() => {
const HAS_PLUGIN_MODEL = api.hasPlugins(['@fesjs/plugin-model']); const HAS_PLUGIN_MODEL = api.hasPlugins(['@fesjs/plugin-model']);
api.writeTmpFile({ api.writeTmpFile({
path: absMicroAppPath, path: absMicroAppPath,
content: Mustache.render( content: Mustache.render(readFileSync(join(__dirname, 'runtime/MicroApp.tpl'), 'utf-8'), {
readFileSync(join(__dirname, 'runtime/MicroApp.tpl'), 'utf-8'),
{
qiankunStateForMicroModelNamespace, qiankunStateForMicroModelNamespace,
HAS_PLUGIN_MODEL: HAS_PLUGIN_MODEL: HAS_PLUGIN_MODEL && existsSync(winPath(join(api.paths.absSrcPath, 'models/qiankunStateForMicro.js'))),
HAS_PLUGIN_MODEL QIANKUN: resolveInnerDep('qiankun', api.builder),
&& existsSync( LODASH_ES: resolveInnerDep('lodash-es', api.builder),
winPath( }),
join(
api.paths.absSrcPath,
'models/qiankunStateForMicro.js'
)
)
),
QIANKUN: resolvePkg('qiankun'),
LODASH_ES: resolvePkg('lodash-es')
}
)
}); });
api.writeTmpFile({ api.writeTmpFile({
path: absMicroAppWithMemoHistoryPath, path: absMicroAppWithMemoHistoryPath,
content: Mustache.render( content: Mustache.render(readFileSync(join(__dirname, 'runtime/MicroAppWithMemoHistory.tpl'), 'utf-8'), {}),
readFileSync(join(__dirname, 'runtime/MicroAppWithMemoHistory.tpl'), 'utf-8'),
{
}
)
}); });
api.writeTmpFile({ api.writeTmpFile({
path: absRuntimePath, path: absRuntimePath,
content: readFileSync( content: readFileSync(join(__dirname, 'runtime/runtime.tpl'), 'utf-8'),
join(__dirname, 'runtime/runtime.tpl'),
'utf-8'
)
}); });
api.writeTmpFile({ api.writeTmpFile({
path: absGetMicroAppRouteCompPath, path: absGetMicroAppRouteCompPath,
content: readFileSync( content: readFileSync(join(__dirname, 'runtime/getMicroAppRouteComponent.tpl'), 'utf-8'),
join(__dirname, 'runtime/getMicroAppRouteComponent.tpl'),
'utf-8'
)
}); });
const { main: options } = api.config?.qiankun || {}; const { main: options } = api.config?.qiankun || {};
@ -100,32 +68,32 @@ export default function (api) {
let options = ${JSON.stringify({ let options = ${JSON.stringify({
masterHistoryType, masterHistoryType,
base, base,
...options ...options,
})}; })};
export const getMasterOptions = () => options; export const getMasterOptions = () => options;
export const setMasterOptions = (newOpts) => options = ({ ...options, ...newOpts }); export const setMasterOptions = (newOpts) => options = ({ ...options, ...newOpts });
` `,
}); });
}); });
api.addPluginExports(() => [ api.addPluginExports(() => [
{ {
specifiers: ['MicroApp'], specifiers: ['MicroApp'],
source: absMicroAppPath source: absMicroAppPath,
} },
]); ]);
api.addPluginExports(() => [ api.addPluginExports(() => [
{ {
specifiers: ['MicroAppWithMemoHistory'], specifiers: ['MicroAppWithMemoHistory'],
source: absMicroAppWithMemoHistoryPath source: absMicroAppWithMemoHistoryPath,
} },
]); ]);
api.addPluginExports(() => [ api.addPluginExports(() => [
{ {
specifiers: ['getMicroAppRouteComponent'], specifiers: ['getMicroAppRouteComponent'],
source: absGetMicroAppRouteCompPath source: absGetMicroAppRouteCompPath,
} },
]); ]);
} }

View File

@ -1,7 +1,7 @@
import { Logger } from '@fesjs/compiler'; import { Logger } from '@fesjs/compiler';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { resolvePkg } from '@fesjs/utils'; import { resolveInnerDep } from '@fesjs/utils';
import { name } from '../package.json'; import { name } from '../package.json';
const logger = new Logger('fes:plugin-request'); const logger = new Logger('fes:plugin-request');
@ -45,7 +45,7 @@ export default (api) => {
content: requestTemplate content: requestTemplate
.replace('REPLACE_DATA_FIELD', JSON.stringify(dataField)) .replace('REPLACE_DATA_FIELD', JSON.stringify(dataField))
.replace('REPLACE_BASE', base || '') .replace('REPLACE_BASE', base || '')
.replace('AXIOS_PATH', resolvePkg('axios')), .replace('AXIOS_PATH', resolveInnerDep('axios', api.builder)),
}); });
}); });
@ -67,13 +67,9 @@ export default (api) => {
}, },
]); ]);
api.addRuntimeType(() => ({ api.addConfigType(() => ({
source: name, source: name,
specifier: ['RequestRuntimeConfig'], runtime: ['RequestRuntimeConfig'],
})); build: ['RequestBuildConfig'],
api.addBuildType(() => ({
source: name,
specifier: ['RequestBuildConfig'],
})); }));
}; };

View File

@ -49,8 +49,8 @@ export default (api) => {
return memo; return memo;
}); });
api.addBuildType(() => ({ api.addConfigType(() => ({
source: name, source: name,
specifier: ['WindicssBuildConfig'], build: ['WindicssBuildConfig'],
})); }));
}; };

View File

@ -1,17 +1,14 @@
function importsToStr(imports) { function importsToStr(imports) {
return imports.map((imp) => { return imports.map((imp) => {
const { source, specifier } = imp; const { source, build = [], runtime = [] } = imp;
if (specifier) { return `import {${build.concat(runtime).join(', ')}} from '${source}';`;
return `import {${specifier.join(', ')}} from '${source}';`;
}
return '';
}); });
} }
function genTypeContent(name, imports) { function genTypeContent(imports) {
return { return {
TYP_NAME: name, RUNTIME_TYPES: imports.reduce((previousValue, currentValue) => previousValue.concat(currentValue.runtime || []), []).join(' & '),
TYPES: imports.reduce((previousValue, currentValue) => previousValue.concat(currentValue.specifier || []), []).join(' & '), BUILD_TYPES: imports.reduce((previousValue, currentValue) => previousValue.concat(currentValue.build || []), []).join(' & '),
imports: importsToStr(imports).join('\n'), imports: importsToStr(imports).join('\n'),
}; };
} }
@ -22,31 +19,20 @@ export default function (api) {
} = api; } = api;
api.onGenerateFiles(async () => { api.onGenerateFiles(async () => {
const runtimeTypeName = 'PluginRuntimeConfig';
const buildTypeName = 'PluginBuildConfig';
const typeTpl = ` const typeTpl = `
{{{ imports }}} {{{ imports }}}
export type {{{TYP_NAME}}} = {{{TYPES}}} export type PluginRuntimeConfig = {{{RUNTIME_TYPES}}};
export type PluginBuildConfig = {{{BUILD_TYPES}}};
`; `;
const runtimeImportSources = await api.applyPlugins({ const importSources = await api.applyPlugins({
key: 'addRuntimeType', key: 'addConfigType',
type: api.ApplyPluginsType.add, type: api.ApplyPluginsType.add,
initialValue: [], initialValue: [],
}); });
api.writeTmpFile({ api.writeTmpFile({
path: 'runtime.d.ts', path: 'configType.d.ts',
content: Mustache.render(typeTpl, genTypeContent(runtimeTypeName, runtimeImportSources)), content: Mustache.render(typeTpl, genTypeContent(importSources)),
});
const buildImportSources = await api.applyPlugins({
key: 'addBuildType',
type: api.ApplyPluginsType.add,
initialValue: [],
});
api.writeTmpFile({
path: 'build.d.ts',
content: Mustache.render(typeTpl, genTypeContent(buildTypeName, buildImportSources)),
}); });
}); });
} }

View File

@ -16,8 +16,7 @@ export default function (api) {
'addEntryCode', 'addEntryCode',
'modifyRoutes', 'modifyRoutes',
'addRuntimeType', 'addConfigType',
'addBuildType',
'addTmpGenerateWatcherPaths', 'addTmpGenerateWatcherPaths',

View File

@ -44,6 +44,6 @@ export default defineBuildConfig({
} }
} }
} }
} },
}); });

View File

@ -29,19 +29,19 @@
} }
}, },
"include": [ "include": [
"*.js",
".fes.js",
"src/**/*", "src/**/*",
"tests/**/*",
"test/**/*",
"__test__/**/*",
"typings/**/*", "typings/**/*",
"config/**/*", "config/**/*",
"src/.fes/runtime.d.ts" "src/.fes/configType.d.ts"
], ],
"exclude": [ "exclude": [
"build", "build",
"dist", "dist",
"scripts", "scripts",
"webpack", "webpack",
"jest" "jest",
"node_modules"
] ]
} }

View File

@ -31,7 +31,8 @@
"config/**/*", "config/**/*",
".eslintrc.js", ".eslintrc.js",
".stylelintrc.js", ".stylelintrc.js",
".prettierrc.js" ".prettierrc.js",
"src/.fes/configType.d.ts"
], ],
"exclude": ["node_modules", "build", "dist", "scripts", "src/.fes/*", "webpack", "jest"] "exclude": ["node_modules", "build", "dist", "scripts", "src/.fes/*", "webpack", "jest"]
} }

View File

@ -20,6 +20,7 @@ import Generator from './Generator';
import winPath from './winPath'; import winPath from './winPath';
import delay from './delay'; import delay from './delay';
import resolvePkg from './resolvePkg'; import resolvePkg from './resolvePkg';
import resolveInnerDep from './resolveInnerDep';
import compatESModuleRequire from './compatESModuleRequire'; import compatESModuleRequire from './compatESModuleRequire';
import cleanRequireCache from './cleanRequireCache'; import cleanRequireCache from './cleanRequireCache';
import parseRequireDeps from './parseRequireDeps'; import parseRequireDeps from './parseRequireDeps';
@ -47,4 +48,16 @@ export {
generator, generator,
}; };
export { Generator, winPath, delay, compatESModuleRequire, cleanRequireCache, parseRequireDeps, mergeConfig, resolvePkg, generateFiles, getAppEntryPath }; export {
Generator,
winPath,
delay,
compatESModuleRequire,
cleanRequireCache,
parseRequireDeps,
mergeConfig,
resolvePkg,
resolveInnerDep,
generateFiles,
getAppEntryPath,
};

View File

@ -0,0 +1,12 @@
import { dirname } from 'path';
import winPath from './winPath';
const resolvePkg = (pkgName, builder) => {
const pkgPath = dirname(require.resolve(`${pkgName}/package.json`));
if (builder.isVite) {
return winPath(pkgPath.replace('/', `${builder.innerDepPrefix}/`));
}
return winPath(pkgPath);
};
export default resolvePkg;

View File

@ -1,8 +1,8 @@
import { Component, DefineComponent, App } from 'vue'; import { Component, DefineComponent, App } from 'vue';
import { RouteRecordRaw, Router } from 'vue-router'; import { RouteRecordRaw, Router } from 'vue-router';
import { Plugin } from '@fesjs/runtime'; import { Plugin } from '@fesjs/runtime';
import { PluginRuntimeConfig } from '@@/runtime'; // @ts-ignore
import { PluginBuildConfig } from '@@/build'; import type { PluginRuntimeConfig, PluginBuildConfig } from '@@/configType';
// @ts-ignore // @ts-ignore
export * from '@@/core/coreExports'; export * from '@@/core/coreExports';