Skip to content

Commit

Permalink
Merge branch 'main' into feature/plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
callqh committed Jun 14, 2024
2 parents 3cffbe2 + 122ab6d commit e7286e5
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 116 deletions.
5 changes: 5 additions & 0 deletions .changeset/few-bobcats-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@farmfe/core": minor
---

optimize @farmfe/core api usage
65 changes: 65 additions & 0 deletions examples/react/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import {
createCompiler,
createDevServer,
createFileWatcher,
resolveConfig,
start,
} from "@farmfe/core";

const resolvedUserConfig = await resolveConfig({
compilation: {
sourcemap: true,
persistentCache: false,
presetEnv: false,
progress: false,
output: {
publicPath: '/dist/'
},
input: {
index: './index.html'
}
},
server: {
port: 6532,
hmr: {
path: '/__farm_hmr'
}
},
plugins: [
'@farmfe/plugin-react',
'@farmfe/plugin-sass'
],
mode: 'development',
});

const compiler = await createCompiler(resolvedUserConfig);

const devServer = await createDevServer(compiler, resolvedUserConfig);

await devServer.listen();

await start({
compilation: {
sourcemap: true,
persistentCache: false,
presetEnv: false,
progress: false,
output: {
publicPath: '/dist/'
},
input: {
index: './index.html'
}
},
server: {
port: 6532,
hmr: {
path: '/__farm_hmr'
}
},
plugins: [
'@farmfe/plugin-react',
'@farmfe/plugin-sass'
],
mode: 'development',
});
2 changes: 1 addition & 1 deletion examples/react/src/components/welcome/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function Welcome() {
<FarmCard>
<div className="main-desc">
<h2 className="main-sub-title">
Get started Withasdasd
Get started With
<span className="main-content"> React + Farm</span>
</h2>
<span className="main-content">
Expand Down
1 change: 0 additions & 1 deletion examples/react/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export function Main() {
const store = useStore();
console.log(process.env.NODE_ENV);
console.log(import.meta);

return (
<>
<div>
Expand Down
5 changes: 5 additions & 0 deletions examples/vite-adapter-vue/components.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export {}

declare module 'vue' {
export interface GlobalComponents {
ElButton: typeof import('element-plus/es')['ElButton']
ElConfigProvider: typeof import('element-plus/es')['ElConfigProvider']
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
ElInput: typeof import('element-plus/es')['ElInput']
ElTree: typeof import('element-plus/es')['ElTree']
Formatter: typeof import('./src/components/Formatter.vue')['default']
HelloWorld: typeof import('./src/components/HelloWorld.vue')['default']
Intro: typeof import('./src/components/Intro.vue')['default']
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Compiler as BindingCompiler } from '../../binding/index.js';

import type { Resource } from '../index.js';
import type { Config, JsUpdateResult } from '../types/binding.js';
import type { ILogger } from '../utils/logger.js';
import { type ILogger, Logger } from '../utils/logger.js';

export const VIRTUAL_FARM_DYNAMIC_IMPORT_SUFFIX =
'.farm_dynamic_import_virtual_module';
Expand Down Expand Up @@ -38,7 +38,7 @@ export class Compiler {

constructor(
public config: Config,
private logger: ILogger
private logger: ILogger = new Logger()
) {
this._bindingCompiler = new BindingCompiler(this.config);
}
Expand Down
95 changes: 48 additions & 47 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,18 @@ export function defineFarmConfig(config: UserConfigExport): UserConfigExport {
async function getDefaultConfig(
config: UserConfig,
inlineOptions: FarmCLIOptions,
logger: Logger,
mode?: CompilationMode
mode?: CompilationMode,
logger?: Logger
) {
logger = logger ?? new Logger();
const resolvedUserConfig = await resolveMergedUserConfig(
config,
undefined,
inlineOptions.mode ?? mode,
logger
);

resolvedUserConfig.server = normalizeDevServerOptions({}, mode);
resolvedUserConfig.server = normalizeDevServerConfig(inlineOptions, mode);

resolvedUserConfig.compilation = await normalizeUserCompilationConfig(
resolvedUserConfig,
Expand Down Expand Up @@ -129,15 +130,16 @@ async function handleServerPortConflict(
* @param configPath
*/
export async function resolveConfig(
inlineOptions: FarmCLIOptions & UserConfig,
logger: Logger,
inlineOptions: FarmCLIOptions & UserConfig = {},
mode?: CompilationMode,
logger?: Logger,
isHandleServerPortConflict = true
): Promise<ResolvedUserConfig> {
// Clear the console according to the cli command

checkClearScreen(inlineOptions);
logger = logger ?? new Logger();
inlineOptions.mode = inlineOptions.mode ?? mode;

// configPath may be file or directory
let { configPath } = inlineOptions;
let rawConfig: UserConfig = mergeFarmCliConfig(inlineOptions, {});
Expand All @@ -163,7 +165,7 @@ export async function resolveConfig(
} else {
mergeConfig(
rawConfig,
await getDefaultConfig(rawConfig, inlineOptions, logger, mode)
await getDefaultConfig(rawConfig, inlineOptions, mode, logger)
);
}

Expand All @@ -172,26 +174,11 @@ export async function resolveConfig(
config: rawConfig
};

const { jsPlugins, rustPlugins } = await resolveFarmPlugins(userConfig);

const rawJsPlugins = (await resolveAsyncPlugins(jsPlugins || [])).filter(
Boolean
);

let vitePluginAdapters: JsPlugin[] = [];
const vitePlugins = (userConfig?.vitePlugins ?? []).filter(Boolean);
// run config and configResolved hook
if (vitePlugins.length) {
vitePluginAdapters = await handleVitePlugins(
vitePlugins,
userConfig,
logger,
mode
);
}
const { jsPlugins, vitePlugins, rustPlugins, vitePluginAdapters } =
await resolvePlugins(userConfig, logger, mode);

const sortFarmJsPlugins = getSortedPlugins([
...rawJsPlugins,
...jsPlugins,
...vitePluginAdapters,
externalAdapter()
]);
Expand All @@ -208,7 +195,7 @@ export async function resolveConfig(
);

// normalize server config first cause it may be used in normalizeUserCompilationConfig
resolvedUserConfig.server = normalizeDevServerOptions(
resolvedUserConfig.server = normalizeDevServerConfig(
resolvedUserConfig.server,
mode
);
Expand Down Expand Up @@ -247,10 +234,6 @@ export async function resolveConfig(
return resolvedUserConfig;
}

// type ServerConfig = {
// server?: NormalizedServerConfig;
// };

/**
* Normalize user config and transform it to rust compiler compatible config
*
Expand Down Expand Up @@ -610,7 +593,7 @@ function tryAsFileRead(value?: any): string | Buffer {
return value;
}

export function normalizeDevServerOptions(
export function normalizeDevServerConfig(
options: UserServerConfig | undefined,
mode: string
): NormalizedServerConfig {
Expand Down Expand Up @@ -820,7 +803,7 @@ export function normalizePublicPath(

function checkClearScreen(inlineConfig: FarmCLIOptions) {
if (
inlineConfig.clearScreen &&
inlineConfig?.clearScreen &&
!__FARM_GLOBAL__.__FARM_RESTART_DEV_SERVER__
) {
clearScreen();
Expand All @@ -831,26 +814,15 @@ export async function resolveMergedUserConfig(
mergedUserConfig: UserConfig,
configFilePath: string | undefined,
mode: 'development' | 'production' | string,
logger: Logger
logger: Logger = new Logger()
): Promise<ResolvedUserConfig> {
const serverConfig: NormalizedServerConfig = {
...DEFAULT_DEV_SERVER_OPTIONS,
...mergedUserConfig.server,
hmr: {
...DEFAULT_HMR_OPTIONS,
...(isObject(mergedUserConfig.server?.hmr)
? mergedUserConfig.server.hmr
: {})
}
};
const resolvedUserConfig: ResolvedUserConfig = {
const resolvedUserConfig = {
...mergedUserConfig,
compilation: {
...mergedUserConfig.compilation,
external: []
},
server: serverConfig
};
}
} as ResolvedUserConfig;

// set internal config
resolvedUserConfig.envMode = mode;
Expand Down Expand Up @@ -1076,3 +1048,32 @@ const transformFarmPluginPath = (importers: string, root: string) => ({
}
}
});
export async function resolvePlugins(
userConfig: UserConfig,
logger: Logger,
mode: CompilationMode
) {
const { jsPlugins, rustPlugins } = await resolveFarmPlugins(userConfig);
const rawJsPlugins = (await resolveAsyncPlugins(jsPlugins || [])).filter(
Boolean
);

let vitePluginAdapters: JsPlugin[] = [];
const vitePlugins = (userConfig?.vitePlugins ?? []).filter(Boolean);

if (vitePlugins.length) {
vitePluginAdapters = await handleVitePlugins(
vitePlugins,
userConfig,
logger,
mode
);
}

return {
jsPlugins: rawJsPlugins,
vitePlugins,
rustPlugins,
vitePluginAdapters
};
}
16 changes: 14 additions & 2 deletions packages/core/src/config/mergeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ export function mergeConfig<T extends Record<string, any>>(

if (isArray(left) || isArray(right)) {
result[key] = [
...(isArray(left) ? left : []),
...(isArray(right) ? right : [])
...new Set([
...(isArray(left) ? left : []),
...(isArray(right) ? right : [])
])
];

continue;
}

Expand Down Expand Up @@ -78,7 +81,10 @@ export function mergeFarmCliConfig(
} else {
target.root = cliRoot;
}
} else {
target.root = process.cwd();
}

if (configRootPath) {
target.root = configRootPath;
}
Expand Down Expand Up @@ -135,3 +141,9 @@ export function mergeFarmCliConfig(

return mergeConfig(left, target);
}

export function initialCliOptions(options: FarmCLIOptions): FarmCLIOptions {
return {
...options
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ export async function normalizePersistentCache(
resolvedUserConfig: ResolvedUserConfig,
logger: Logger
) {
if (
config?.persistentCache === false ||
resolvedUserConfig.configFilePath === undefined
) {
if (config?.persistentCache === false) {
return;
}

Expand Down Expand Up @@ -151,7 +148,6 @@ export async function normalizePersistentCache(
packages.push(...(rustPlugins ?? []));

if (packages?.length) {
// console.log('packages', config);
const require = createRequire(path.join(config.root, 'package.json'));

for (const p of packages) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export interface UserPreviewServerConfig {

export type NormalizedServerConfig = Required<
Omit<UserServerConfig, 'hmr'> & {
hmr: Required<UserHmrConfig>;
hmr?: Required<UserHmrConfig>;
}
>;

Expand Down

0 comments on commit e7286e5

Please sign in to comment.