feat: 增加乾坤构建提示

This commit is contained in:
wanchun 2022-03-29 11:06:45 +08:00
parent 0816e25905
commit 59ca087b23
6 changed files with 90 additions and 123 deletions

View File

@ -41,5 +41,6 @@
"@fesjs/fes": "^2.0.0", "@fesjs/fes": "^2.0.0",
"@fesjs/fes-design": "^0.1.10", "@fesjs/fes-design": "^0.1.10",
"vue": "^3.0.5" "vue": "^3.0.5"
} },
"typings": "./types.d.ts"
} }

View File

@ -5,16 +5,13 @@ export default (api) => {
schema(joi) { schema(joi) {
return joi.object().keys({ return joi.object().keys({
micro: joi.object(), micro: joi.object(),
main: joi.object() main: joi.object(),
}); });
} },
} },
}); });
api.addRuntimePluginKey(() => 'qiankun'); api.addRuntimePluginKey(() => 'qiankun');
api.registerPlugins([ api.registerPlugins([require.resolve('./main'), require.resolve('./micro')]);
require.resolve('./main'),
require.resolve('./micro')
]);
}; };

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 { resolvePkg } 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
&& existsSync(
winPath(
join(
api.paths.absSrcPath,
'models/qiankunStateForMicro.js'
)
)
),
QIANKUN: resolvePkg('qiankun'), QIANKUN: resolvePkg('qiankun'),
LODASH_ES: resolvePkg('lodash-es') 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,18 +1,16 @@
import { defaultHistoryType } from '../constants'; import { defaultHistoryType } from '../constants';
function getMicroApp(options) { function getMicroApp(options) {
const { const { key, microAppName, masterHistoryType, base, namespace, ...normalizedRouteProps } = options;
key, microAppName, masterHistoryType, base, namespace, ...normalizedRouteProps
} = options;
return `(() => { return `(() => {
const { getMicroAppRouteComponent } = require('@@/${namespace}/getMicroAppRouteComponent'); const { getMicroAppRouteComponent } = require('@@/${namespace}/getMicroAppRouteComponent');
return getMicroAppRouteComponent({key: '${key}', appName: '${microAppName}', base: '${base}', masterHistoryType: '${masterHistoryType}', routeProps: ${JSON.stringify(normalizedRouteProps)} }) return getMicroAppRouteComponent({key: '${key}', appName: '${microAppName}', base: '${base}', masterHistoryType: '${masterHistoryType}', routeProps: ${JSON.stringify(
normalizedRouteProps,
)} })
})()`; })()`;
} }
function modifyRoutesWithAttachMode({ function modifyRoutesWithAttachMode({ routes, masterHistoryType, base, namespace }) {
routes, masterHistoryType, base, namespace
}) {
const patchRoutes = (_routes) => { const patchRoutes = (_routes) => {
if (_routes.length) { if (_routes.length) {
_routes.forEach((route) => { _routes.forEach((route) => {
@ -22,7 +20,7 @@ function modifyRoutesWithAttachMode({
microAppName: route.meta.microApp, microAppName: route.meta.microApp,
masterHistoryType, masterHistoryType,
base, base,
namespace namespace,
}); });
} }
if (route.children?.length) { if (route.children?.length) {
@ -30,7 +28,7 @@ function modifyRoutesWithAttachMode({
routes: route.children, routes: route.children,
masterHistoryType, masterHistoryType,
base, base,
namespace namespace,
}); });
} }
}); });
@ -51,7 +49,7 @@ export default function modifyRoutes({ api, namespace }) {
routes, routes,
masterHistoryType, masterHistoryType,
base: base || '/', base: base || '/',
namespace namespace,
}); });
return routes; return routes;

View File

@ -8,39 +8,34 @@ import { qiankunStateFromMainModelNamespace } from '../constants';
const namespace = 'plugin-qiankun/micro'; const namespace = 'plugin-qiankun/micro';
export function isSlaveEnable(api) { export function isSlaveEnable(api) {
return ( return !!api.userConfig?.qiankun?.micro || lodash.isEqual(api.userConfig?.qiankun, {}) || !!process.env.INITIAL_QIANKUN_MIRCO_OPTIONS;
!!api.userConfig?.qiankun?.micro
|| lodash.isEqual(api.userConfig?.qiankun, {})
|| !!process.env.INITIAL_QIANKUN_MIRCO_OPTIONS
);
} }
export default function (api) { export default function (api) {
const { const {
utils: { Mustache } utils: { Mustache },
} = api; } = api;
api.describe({ api.describe({
enableBy: () => isSlaveEnable(api) enableBy: () => isSlaveEnable(api),
}); });
api.modifyDefaultConfig((memo) => { api.modifyDefaultConfig((memo) => {
const initialMicroOptions = { const initialMicroOptions = {
devSourceMap: true, devSourceMap: true,
...JSON.parse(process.env.INITIAL_QIANKUN_MIRCO_OPTIONS || '{}'), ...JSON.parse(process.env.INITIAL_QIANKUN_MIRCO_OPTIONS || '{}'),
...(memo.qiankun || {}).micro ...(memo.qiankun || {}).micro,
}; };
const modifiedDefaultConfig = { const modifiedDefaultConfig = {
...memo, ...memo,
runtimePublicPath: true, runtimePublicPath: true,
qiankun: { qiankun: {
...memo.qiankun, ...memo.qiankun,
slave: initialMicroOptions slave: initialMicroOptions,
} },
}; };
const shouldNotModifyDefaultBase = api.userConfig.qiankun?.slave?.shouldNotModifyDefaultBase const shouldNotModifyDefaultBase = api.userConfig.qiankun?.slave?.shouldNotModifyDefaultBase ?? initialMicroOptions.shouldNotModifyDefaultBase;
?? initialMicroOptions.shouldNotModifyDefaultBase;
if (!shouldNotModifyDefaultBase) { if (!shouldNotModifyDefaultBase) {
modifiedDefaultConfig.base = `/${api.pkg.name}`; modifiedDefaultConfig.base = `/${api.pkg.name}`;
} }
@ -57,19 +52,13 @@ export default function (api) {
const port = process.env.PORT; const port = process.env.PORT;
// source-map 跨域设置 // source-map 跨域设置
if (process.env.NODE_ENV === 'development' && port) { if (process.env.NODE_ENV === 'development' && port) {
const localHostname = process.env.USE_REMOTE_IP const localHostname = process.env.USE_REMOTE_IP ? address.ip() : process.env.HOST || 'localhost';
? address.ip()
: process.env.HOST || 'localhost';
const protocol = process.env.HTTPS ? 'https' : 'http'; const protocol = process.env.HTTPS ? 'https' : 'http';
// TODO: 变更 webpack-dev-server websocket 默认监听地址 // TODO: 变更 webpack-dev-server websocket 默认监听地址
api.chainWebpack((memo, { webpack }) => { api.chainWebpack((memo, { webpack }) => {
// 开启了 devSourceMap 配置,默认为 true // 开启了 devSourceMap 配置,默认为 true
if ( if (api.config.qiankun && api.config.qiankun.micro && api.config.qiankun.micro.devSourceMap !== false) {
api.config.qiankun
&& api.config.qiankun.micro
&& api.config.qiankun.micro.devSourceMap !== false
) {
// 禁用 devtool启用 SourceMapDevToolPlugin // 禁用 devtool启用 SourceMapDevToolPlugin
memo.devtool(false); memo.devtool(false);
memo.plugin('source-map').use(webpack.SourceMapDevToolPlugin, [ memo.plugin('source-map').use(webpack.SourceMapDevToolPlugin, [
@ -77,8 +66,8 @@ export default function (api) {
// @ts-ignore // @ts-ignore
namespace: api.pkg.name, namespace: api.pkg.name,
append: `\n//# sourceMappingURL=${protocol}://${localHostname}:${port}/[url]`, append: `\n//# sourceMappingURL=${protocol}://${localHostname}:${port}/[url]`,
filename: '[file].map' filename: '[file].map',
} },
]); ]);
} }
return memo; return memo;
@ -98,11 +87,15 @@ export default function (api) {
key: 'addExtraModels', key: 'addExtraModels',
fn: () => { fn: () => {
const HAS_PLUGIN_MODEL = api.hasPlugins(['@fesjs/plugin-model']); const HAS_PLUGIN_MODEL = api.hasPlugins(['@fesjs/plugin-model']);
return HAS_PLUGIN_MODEL ? [{ return HAS_PLUGIN_MODEL
? [
{
absPath: `@@/${absModelPath}`, absPath: `@@/${absModelPath}`,
namespace: qiankunStateFromMainModelNamespace namespace: qiankunStateFromMainModelNamespace,
}] : []; },
} ]
: [];
},
}); });
api.onGenerateFiles(() => { api.onGenerateFiles(() => {
@ -110,20 +103,14 @@ export default function (api) {
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: absLifeclesPath, path: absLifeclesPath,
content: Mustache.render(readFileSync( content: Mustache.render(readFileSync(join(__dirname, 'runtime/lifecycles.tpl'), 'utf-8'), {
join(__dirname, 'runtime/lifecycles.tpl'), HAS_PLUGIN_MODEL,
'utf-8' }),
), {
HAS_PLUGIN_MODEL
})
}); });
api.writeTmpFile({ api.writeTmpFile({
@ -133,24 +120,22 @@ export default function (api) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
window.public_path = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; window.public_path = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
} }
` `,
}); });
api.writeTmpFile({ api.writeTmpFile({
path: absMicroOptionsPath, path: absMicroOptionsPath,
content: ` content: `
let options = ${JSON.stringify( let options = ${JSON.stringify((api.config.qiankun || {}).micro || {})};
(api.config.qiankun || {}).micro || {}
)};
export const getSlaveOptions = () => options; export const getSlaveOptions = () => options;
export const setSlaveOptions = (newOpts) => options = ({ ...options, ...newOpts }); export const setSlaveOptions = (newOpts) => options = ({ ...options, ...newOpts });
` `,
}); });
if (HAS_PLUGIN_MODEL) { if (HAS_PLUGIN_MODEL) {
api.writeTmpFile({ api.writeTmpFile({
path: absModelPath, path: absModelPath,
content: readFileSync(join(__dirname, 'runtime/qiankunModel.tpl'), 'utf-8') content: readFileSync(join(__dirname, 'runtime/qiankunModel.tpl'), 'utf-8'),
}); });
} }
}); });
@ -159,8 +144,7 @@ export default function (api) {
api.addEntryImports(() => ({ api.addEntryImports(() => ({
source: `@@/${absLifeclesPath}`, source: `@@/${absLifeclesPath}`,
specifier: specifier: '{ genMount as qiankun_genMount, genBootstrap as qiankun_genBootstrap, genUnmount as qiankun_genUnmount, genUpdate as qiankun_genUpdate }',
'{ genMount as qiankun_genMount, genBootstrap as qiankun_genBootstrap, genUnmount as qiankun_genUnmount, genUpdate as qiankun_genUpdate }'
})); }));
api.addEntryCode( api.addEntryCode(
@ -173,6 +157,6 @@ export const update = qiankun_genUpdate();
if (!window.__POWERED_BY_QIANKUN__) { if (!window.__POWERED_BY_QIANKUN__) {
bootstrap().then(mount); bootstrap().then(mount);
} }
` `,
); );
} }

19
packages/fes-plugin-qiankun/types.d.ts vendored Normal file
View File

@ -0,0 +1,19 @@
import { FrameworkLifeCycles, MicroApp } from 'qiankun';
interface AppOption {
name: string;
entry: string;
props: Record<string, any>;
}
export interface QiankunBuildConfig {
qiankun: {
main: {
apps: AppOption[];
lifeCycles?: FrameworkLifeCycles<MicroApp>;
[key: string]: any;
};
micro: {}
};
}