Skip to content

Commit

Permalink
chore: perf core code
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Aug 8, 2024
1 parent a294eba commit 04b8c5f
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 64 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"biome.enabled": true,
"editor.defaultFormatter": "biomejs.biome",
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "biomejs.biome"
Expand Down
61 changes: 26 additions & 35 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,7 @@ export class Compiler {
}

async compile() {
if (this.compiling) {
this.logger.error('Already compiling', {
exit: true
});
}
this.checkCompiling();

this.compiling = true;
if (process.env.FARM_PROFILE) {
Expand All @@ -80,11 +76,8 @@ export class Compiler {
}

compileSync() {
if (this.compiling) {
this.logger.error('Already compiling', {
exit: true
});
}
this.checkCompiling();

this.compiling = true;
this._bindingCompiler.compileSync();
this.compiling = false;
Expand Down Expand Up @@ -163,22 +156,16 @@ export class Compiler {
}

pluginStats() {
return this._bindingCompiler.pluginStats() as PluginStats;
return this._bindingCompiler.pluginStats();
}

writeResourcesToDisk(): void {
const resources = this.resources();
const configOutputPath = this.config.config.output.path;
const outputPath = path.isAbsolute(configOutputPath)
? configOutputPath
: path.join(this.config.config.root, configOutputPath);
const outputPath = this.getOutputPath();

for (const [name, resource] of Object.entries(resources)) {
// remove query params and hash of name
const nameWithoutQuery = name.split('?')[0];
const nameWithoutHash = nameWithoutQuery.split('#')[0];
const filePath = path.join(outputPath, name.split(/[?#]/)[0]);

let filePath = path.join(outputPath, nameWithoutHash);
if (!existsSync(path.dirname(filePath))) {
mkdirSync(path.dirname(filePath), { recursive: true });
}
Expand All @@ -190,7 +177,7 @@ export class Compiler {
}

callWriteResourcesHook() {
for (const jsPlugin of this.config.jsPlugins ?? []) {
for (const jsPlugin of this.config.jsPlugins) {
jsPlugin.writeResources?.executor?.({
resourcesMap: this._bindingCompiler.resourcesMap() as Record<
string,
Expand Down Expand Up @@ -223,28 +210,15 @@ export class Compiler {
p = p.slice(0, -VIRTUAL_FARM_DYNAMIC_IMPORT_SUFFIX.length);
}

if (path.isAbsolute(p)) {
return p;
}

if (p.includes('?')) {
return path.join(root, p.split('?')[0]);
}

return path.join(root, p);
return path.isAbsolute(p) ? p : path.join(root, p.split('?')[0]);
}

onUpdateFinish(cb: () => void) {
this._onUpdateFinishQueue.push(cb);
}

outputPath() {
const { output, root } = this.config.config;
const configOutputPath = output.path;
const outputPath = path.isAbsolute(configOutputPath)
? configOutputPath
: path.join(root, configOutputPath);
return outputPath;
return this.getOutputPath();
}

addExtraWatchFile(root: string, paths: string[]) {
Expand Down Expand Up @@ -274,4 +248,21 @@ export class Compiler {
getResourcePotRecordsById(id: string) {
return this._bindingCompiler.getResourcePotRecordsById(id);
}

private checkCompiling() {
if (this.compiling) {
this.logger.error('Already compiling', {
exit: true
});
}
}

private getOutputPath(): string {
const { output, root } = this.config.config;
const configOutputPath = output.path;
const outputPath = path.isAbsolute(configOutputPath)
? configOutputPath
: path.join(root, configOutputPath);
return outputPath;
}
}
36 changes: 34 additions & 2 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { parseUserConfig } from './schema.js';

import { externalAdapter } from '../plugin/js/external-adapter.js';
import { convertErrorMessage } from '../utils/error.js';
import { resolveHostname } from '../utils/http.js';
import merge from '../utils/merge.js';
import {
CUSTOM_KEYS,
Expand Down Expand Up @@ -93,14 +94,14 @@ export function defineFarmConfig(config: UserConfigExport): UserConfigExport {
*/
export async function resolveConfig(
inlineOptions: FarmCliOptions & UserConfig,
command: 'start' | 'build' | 'preview',
command: 'start' | 'build' | 'watch' | 'preview',
defaultMode: CompilationMode = 'development',
defaultNodeEnv: CompilationMode = 'development',
isPreview = false,
logger?: Logger
): Promise<ResolvedUserConfig> {
logger = logger ?? new Logger();

// TODO mode 这块还是不对 要区分 mode 和 build 还是 dev 环境
const compileMode = defaultMode;
const mode = inlineOptions.mode || defaultMode;
const isNodeEnvSet = !!process.env.NODE_ENV;
Expand Down Expand Up @@ -193,6 +194,25 @@ export async function resolveConfig(
resolvedUserConfig.compilation.resolve.alias as unknown as Array<Alias>
);
}

switch (configEnv.command) {
case 'start':
if (
resolvedUserConfig.compilation.lazyCompilation &&
typeof resolvedUserConfig.server?.host === 'string'
) {
await setLazyCompilationDefine(resolvedUserConfig);
}
break;
case 'watch':
if (resolvedUserConfig.compilation?.lazyCompilation) {
await setLazyCompilationDefine(resolvedUserConfig);
}
break;
default:
break;
}

return resolvedUserConfig;
}

Expand Down Expand Up @@ -1022,3 +1042,15 @@ export function getFilePath(outputPath: string, fileName: string): string {
? pathToFileURL(path.join(outputPath, fileName)).toString()
: path.join(outputPath, fileName);
}

async function setLazyCompilationDefine(
resolvedUserConfig: ResolvedUserConfig
) {
const hostname = await resolveHostname(resolvedUserConfig.server.host);
resolvedUserConfig.compilation.define = {
...(resolvedUserConfig.compilation.define ?? {}),
FARM_LAZY_COMPILE_SERVER_URL: `${
resolvedUserConfig.server.protocol || 'http'
}://${hostname.host || 'localhost'}:${resolvedUserConfig.server.port}`
};
}
27 changes: 1 addition & 26 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ import { lazyCompilation } from './server/middlewares/lazy-compilation.js';
import { ConfigWatcher } from './watcher/config-watcher.js';

import type { JsPlugin } from './plugin/type.js';
import { resolveHostname } from './utils/http.js';

export async function start(
inlineConfig?: FarmCliOptions & UserConfig
Expand All @@ -73,13 +72,6 @@ export async function start(
false
);

if (
resolvedUserConfig.compilation.lazyCompilation &&
typeof resolvedUserConfig.server?.host === 'string'
) {
await setLazyCompilationDefine(resolvedUserConfig);
}

const compiler = await createCompiler(resolvedUserConfig, logger);

const devServer = await createDevServer(
Expand Down Expand Up @@ -181,12 +173,6 @@ export async function watch(
logger
);

const lazyEnabled = resolvedUserConfig.compilation?.lazyCompilation;

if (lazyEnabled) {
await setLazyCompilationDefine(resolvedUserConfig);
}

const compilerFileWatcher = await createBundleHandler(
resolvedUserConfig,
logger,
Expand All @@ -195,6 +181,7 @@ export async function watch(

let devServer: Server | undefined;
// create dev server for lazy compilation
const lazyEnabled = resolvedUserConfig.compilation.lazyCompilation;
if (lazyEnabled) {
devServer = new Server({
logger,
Expand Down Expand Up @@ -456,18 +443,6 @@ export function logFileChanges(files: string[], root: string, logger: Logger) {
);
}

async function setLazyCompilationDefine(
resolvedUserConfig: ResolvedUserConfig
) {
const hostname = await resolveHostname(resolvedUserConfig.server.host);
resolvedUserConfig.compilation.define = {
...(resolvedUserConfig.compilation.define ?? {}),
FARM_LAZY_COMPILE_SERVER_URL: `${
resolvedUserConfig.server.protocol || 'http'
}://${hostname.host || 'localhost'}:${resolvedUserConfig.server.port}`
};
}

export { defineFarmConfig as defineConfig } from './config/index.js';

export { loadEnv };

0 comments on commit 04b8c5f

Please sign in to comment.