fix: dev load plugin (#2455)

* fix: dev load plugin

* fix: bug

* fix: bug
This commit is contained in:
jack zhang 2023-08-20 18:10:34 +08:00 committed by GitHub
parent a59ed4ee17
commit 9e99b00182
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 87 additions and 49 deletions

View File

@ -10,7 +10,7 @@ process.env.DID_YOU_KNOW = 'none';
const pluginPrefix = (process.env.PLUGIN_PACKAGE_PREFIX || '').split(',').filter((item) => !item.includes('preset')); // 因为现在 preset 是直接引入的,所以不能忽略,如果以后 preset 也是动态插件的形式引入,那么这里可以去掉 const pluginPrefix = (process.env.PLUGIN_PACKAGE_PREFIX || '').split(',').filter((item) => !item.includes('preset')); // 因为现在 preset 是直接引入的,所以不能忽略,如果以后 preset 也是动态插件的形式引入,那么这里可以去掉
const pluginDirs = 'packages/plugins/,packages/samples/'.split(',').map((item) => path.join(process.cwd(), item)); const pluginDirs = 'packages/plugins/,packages/samples/'.split(',').map((item) => path.join(process.cwd(), item));
const outputPluginPath = path.join(__dirname, 'src', '.plugins', 'index.ts'); const outputPluginPath = path.join(__dirname, 'src', '.plugins');
const indexGenerator = new IndexGenerator(outputPluginPath, pluginDirs); const indexGenerator = new IndexGenerator(outputPluginPath, pluginDirs);
indexGenerator.generate(); indexGenerator.generate();

View File

@ -1,13 +1,13 @@
import { Application } from '@nocobase/client'; import { Application } from '@nocobase/client';
import { NocoBaseClientPresetPlugin } from '@nocobase/preset-nocobase/client'; import { NocoBaseClientPresetPlugin } from '@nocobase/preset-nocobase/client';
import devPlugins from '../.plugins/index'; import devDynamicImport from '../.plugins/index';
export const app = new Application({ export const app = new Application({
apiClient: { apiClient: {
baseURL: process.env.API_BASE_URL, baseURL: process.env.API_BASE_URL,
}, },
plugins: [NocoBaseClientPresetPlugin], plugins: [NocoBaseClientPresetPlugin],
devPlugins, devDynamicImport,
}); });
export default app.getRootComponent(); export default app.getRootComponent();

View File

@ -24,6 +24,7 @@ declare global {
} }
} }
export type DevDynamicImport = (packageName: string) => Promise<{ default: typeof Plugin }>;
export type ComponentAndProps<T = any> = [ComponentType, T]; export type ComponentAndProps<T = any> = [ComponentType, T];
export interface ApplicationOptions { export interface ApplicationOptions {
apiClient?: APIClientOptions; apiClient?: APIClientOptions;
@ -33,7 +34,7 @@ export interface ApplicationOptions {
components?: Record<string, ComponentType>; components?: Record<string, ComponentType>;
scopes?: Record<string, any>; scopes?: Record<string, any>;
router?: RouterOptions; router?: RouterOptions;
devPlugins?: Record<string, Promise<{ default: typeof Plugin }>>; devDynamicImport?: DevDynamicImport;
} }
export class Application { export class Application {
@ -44,12 +45,12 @@ export class Application {
public apiClient: APIClient; public apiClient: APIClient;
public components: Record<string, ComponentType> = { ...defaultAppComponents }; public components: Record<string, ComponentType> = { ...defaultAppComponents };
public pm: PluginManager; public pm: PluginManager;
public devPlugins: Record<string, Promise<{ default: typeof Plugin }>> = {}; public devDynamicImport: DevDynamicImport;
public requirejs: RequireJS; public requirejs: RequireJS;
constructor(protected options: ApplicationOptions = {}) { constructor(protected options: ApplicationOptions = {}) {
this.initRequireJs(); this.initRequireJs();
this.devPlugins = options.devPlugins || {}; this.devDynamicImport = options.devDynamicImport;
this.scopes = merge(this.scopes, options.scopes); this.scopes = merge(this.scopes, options.scopes);
this.components = merge(this.components, options.components); this.components = merge(this.components, options.components);
this.apiClient = new APIClient(options.apiClient); this.apiClient = new APIClient(options.apiClient);

View File

@ -17,7 +17,10 @@ export class PluginManager {
protected pluginsAliases: Record<string, Plugin> = {}; protected pluginsAliases: Record<string, Plugin> = {};
private initPlugins: Promise<void>; private initPlugins: Promise<void>;
constructor(protected _plugins: PluginType[], protected app: Application) { constructor(
protected _plugins: PluginType[],
protected app: Application,
) {
this.app = app; this.app = app;
this.initPlugins = this.init(_plugins); this.initPlugins = this.init(_plugins);
} }
@ -43,7 +46,7 @@ export class PluginManager {
requirejs: this.app.requirejs, requirejs: this.app.requirejs,
pluginData: pluginList, pluginData: pluginList,
baseURL: this.app.apiClient.axios?.defaults?.baseURL, baseURL: this.app.apiClient.axios?.defaults?.baseURL,
devPlugins: this.app.devPlugins, devDynamicImport: this.app.devDynamicImport,
}); });
for await (const plugin of plugins) { for await (const plugin of plugins) {
await this.add(plugin); await this.add(plugin);

View File

@ -1,6 +1,7 @@
import type { Plugin } from '../Plugin'; import type { Plugin } from '../Plugin';
import type { PluginData } from '../PluginManager'; import type { PluginData } from '../PluginManager';
import type { RequireJS } from './requirejs'; import type { RequireJS } from './requirejs';
import type { DevDynamicImport } from '../Application';
export function defineDevPlugins(plugins: Record<string, typeof Plugin>) { export function defineDevPlugins(plugins: Record<string, typeof Plugin>) {
Object.entries(plugins).forEach(([name, plugin]) => { Object.entries(plugins).forEach(([name, plugin]) => {
@ -44,11 +45,11 @@ interface GetPluginsOption {
requirejs: RequireJS; requirejs: RequireJS;
pluginData: PluginData[]; pluginData: PluginData[];
baseURL?: string; baseURL?: string;
devPlugins?: Record<string, Promise<{ default: typeof Plugin }>>; devDynamicImport?: DevDynamicImport;
} }
export async function getPlugins(options: GetPluginsOption): Promise<Array<typeof Plugin>> { export async function getPlugins(options: GetPluginsOption): Promise<Array<typeof Plugin>> {
const { requirejs, pluginData, baseURL, devPlugins = {} } = options; const { requirejs, pluginData, baseURL, devDynamicImport } = options;
if (pluginData.length === 0) return []; if (pluginData.length === 0) return [];
@ -57,16 +58,18 @@ export async function getPlugins(options: GetPluginsOption): Promise<Array<typeo
const resolveDevPlugins: Record<string, typeof Plugin> = {}; const resolveDevPlugins: Record<string, typeof Plugin> = {};
const pluginPackageNames = pluginData.map((item) => item.packageName); const pluginPackageNames = pluginData.map((item) => item.packageName);
for await (const packageName of pluginPackageNames) { if (devDynamicImport) {
if (devPlugins[packageName]) { for await (const packageName of pluginPackageNames) {
const plugin = await devPlugins[packageName]; const plugin = await devDynamicImport(packageName);
plugins.push(plugin.default); if (plugin) {
resolveDevPlugins[packageName] = plugin.default; plugins.push(plugin.default);
resolveDevPlugins[packageName] = plugin.default;
}
} }
defineDevPlugins(resolveDevPlugins);
} }
defineDevPlugins(resolveDevPlugins);
const remotePlugins = pluginData.filter((item) => !devPlugins[item.packageName]); const remotePlugins = pluginData.filter((item) => !resolveDevPlugins[item.packageName]);
if (remotePlugins.length === 0) { if (remotePlugins.length === 0) {
return plugins; return plugins;

View File

@ -105,70 +105,101 @@ class IndexGenerator {
this.pluginsPath = pluginsPath; this.pluginsPath = pluginsPath;
} }
get indexPath() {
return path.join(this.outputPath, 'index.ts');
}
get packageMapPath() {
return path.join(this.outputPath, 'packageMap.json');
}
get packagesPath() {
return path.join(this.outputPath, 'packages');
}
generate() { generate() {
this.generatePluginIndex(); this.generatePluginContent();
if (process.env.NODE_ENV === 'production') return; if (process.env.NODE_ENV === 'production') return;
this.pluginsPath.forEach((pluginPath) => { this.pluginsPath.forEach((pluginPath) => {
if (!fs.existsSync(pluginPath)) { if (!fs.existsSync(pluginPath)) {
return; return;
} }
fs.watch(pluginPath, { recursive: false }, () => { fs.watch(pluginPath, { recursive: false }, () => {
this.generatePluginIndex(); this.generatePluginContent();
}); });
}); });
} }
generatePluginIndex() { get indexContent() {
if (!fs.existsSync(this.outputPath)) { return `// @ts-nocheck
fs.mkdirSync(path.dirname(this.outputPath), { recursive: true }); import packageMap from './packageMap.json';
fs.writeFileSync(this.outputPath, 'export default {}');
function devDynamicImport(packageName: string): Promise<any> {
const fileName = packageMap[packageName];
if (!fileName) {
return Promise.resolve(null);
}
return import(\`./packages/\${fileName}\`)
}
export default devDynamicImport;`;
}
get emptyIndexContent() {
return `
export default function devDynamicImport(packageName: string): Promise<any> {
return Promise.resolve(null);
}`;
}
generatePluginContent() {
if (fs.existsSync(this.outputPath)) {
fs.rmdirSync(this.outputPath, { recursive: true, force: true });
} }
fs.mkdirSync(this.outputPath);
const validPluginPaths = this.pluginsPath.filter((pluginPath) => fs.existsSync(pluginPath)); const validPluginPaths = this.pluginsPath.filter((pluginPath) => fs.existsSync(pluginPath));
if (!validPluginPaths.length) { if (!validPluginPaths.length || process.env.NODE_ENV === 'production') {
fs.writeFileSync(this.indexPath, this.emptyIndexContent);
return; return;
} }
if (process.env.NODE_ENV === 'production') {
fs.writeFileSync(this.outputPath, 'export default {}');
return;
}
const pluginInfo = validPluginPaths.map((pluginPath) => this.getContent(pluginPath));
const importContent = pluginInfo.map(({ indexContent }) => indexContent).join('\n');
const exportContent = pluginInfo.map(({ exportContent }) => exportContent).join('\n');
const fileContent = `${importContent}\n\nexport default {\n${exportContent}\n}`; const pluginInfos = validPluginPaths.map((pluginPath) => this.getContent(pluginPath)).flat();
fs.writeFileSync(this.outputPath, fileContent); // index.ts
fs.writeFileSync(this.indexPath, this.indexContent);
// packageMap.json
const packageMapContent = pluginInfos.reduce((memo, item) => {
memo[item.packageJsonName] = item.pluginFileName + '.ts';
return memo;
}, {});
fs.writeFileSync(this.packageMapPath, JSON.stringify(packageMapContent, null, 2));
// packages
fs.mkdirSync(this.packagesPath, { recursive: true });
pluginInfos.forEach((item) => {
const pluginPackagePath = path.join(this.packagesPath, item.pluginFileName + '.ts');
fs.writeFileSync(pluginPackagePath, item.exportStatement);
});
} }
getContent(pluginPath) { getContent(pluginPath) {
const pluginFolders = fs.readdirSync(pluginPath); const pluginFolders = fs.readdirSync(pluginPath);
const pluginImports = pluginFolders const pluginInfos = pluginFolders
.filter((folder) => { .filter((folder) => {
const pluginPackageJsonPath = path.join(pluginPath, folder, 'package.json'); const pluginPackageJsonPath = path.join(pluginPath, folder, 'package.json');
const pluginSrcClientPath = path.join(pluginPath, folder, 'src', 'client'); const pluginSrcClientPath = path.join(pluginPath, folder, 'src', 'client');
return fs.existsSync(pluginPackageJsonPath) && fs.existsSync(pluginSrcClientPath); return fs.existsSync(pluginPackageJsonPath) && fs.existsSync(pluginSrcClientPath);
}) })
.map((folder, index) => { .map((folder) => {
const pluginPackageJsonPath = path.join(pluginPath, folder, 'package.json'); const pluginPackageJsonPath = path.join(pluginPath, folder, 'package.json');
const pluginPackageJson = require(pluginPackageJsonPath); const pluginPackageJson = require(pluginPackageJsonPath);
const pluginSrcClientPath = path const pluginSrcClientPath = path
.relative(path.dirname(this.outputPath), path.join(pluginPath, folder, 'src', 'client')) .relative(this.packagesPath, path.join(pluginPath, folder, 'src', 'client'))
.replaceAll('\\', '/'); .replaceAll('\\', '/');
const pluginName = `${folder.replaceAll('-', '_')}${index}`; const pluginFileName = `${path.basename(pluginPath)}_${folder.replaceAll('-', '_')}`;
const importStatement = `const ${pluginName} = import('${pluginSrcClientPath}');`; const exportStatement = `export { default } from '${pluginSrcClientPath}';`;
return { importStatement, pluginName, packageJsonName: pluginPackageJson.name }; return { exportStatement, pluginFileName, packageJsonName: pluginPackageJson.name };
}); });
const indexContent = pluginImports.map(({ importStatement }) => importStatement).join('\n'); return pluginInfos;
const exportContent = pluginImports
.map(({ pluginName, packageJsonName }) => ` "${packageJsonName}": ${pluginName},`)
.join('\n');
return {
indexContent,
exportContent,
};
} }
} }