Skip to content

Commit

Permalink
chore: optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
ErKeLost committed Dec 17, 2024
1 parent d197a5b commit 4b27ff7
Show file tree
Hide file tree
Showing 20 changed files with 86 additions and 119 deletions.
40 changes: 1 addition & 39 deletions examples/arco-pro/farm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,16 @@ import farmJsPluginLess from '@farmfe/js-plugin-less';
export default defineConfig((env) => {
return {
compilation: {
input: {
index: './index.html'
},
sourcemap: false,
presetEnv: false,
concatenateModules: true,
persistentCache: false,
lazyCompilation: false,
resolve: {
symlinks: true,
alias: {
'@': resolve(process.cwd(), './src'),
'react-dom': resolve(process.cwd(), './node_modules/react-dom'),
react: resolve(process.cwd(), './node_modules/react')
}
},
// minify: false,
// mode: 'development',
// persistentCache: false,
output: {
path: './build',
filename: 'assets/[resourceName].[contentHash].[ext]',
assetsFilename: 'static/[resourceName].[contentHash].[ext]'
},
partialBundling: {
targetMinSize: 1024 * 2000,
groups: [
{
name: 'components',
test: ['src/components/.+'],
enforce: true,
},
{
name: 'xxxx',
test: ['src/pages/.+']
}
]
},
progress: false
},
plugins: [
[
'@farmfe/plugin-react',
{
refresh: env.mode === 'development',
development: env.mode === 'development'
}
],
'@farmfe/plugin-react',
'@farmfe/plugin-svgr',
farmJsPluginLess(),
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ setupMock({
{
"id|+1": 1,
username: "用户7352772",
content: "马上就开始了,好激动!",
content: "马上就开始了,好激动!13213222",
time: "13:09:12",
"isCollect|2": true
}
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { readFileSync } from 'node:fs';
import { isAbsolute, resolve } from 'node:path';

import { Logger } from '@farmfe/core';

import type { build, clean, preview, start } from '@farmfe/core';
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/compiler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';

import { Compiler as BindingCompiler } from '../../binding/index.js';

import type {
ResolvedCompilation,
ResolvedUserConfig,
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/config/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,6 @@ const { version } = JSON.parse(
);

export const VERSION = version;

export const ENV_PRODUCTION = 'production';
export const ENV_DEVELOPMENT = 'development';
1 change: 1 addition & 0 deletions packages/core/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import path from 'node:path';

import { parse } from 'dotenv';
import { type DotenvPopulateInput, expand } from 'dotenv-expand';

import { arraify, normalizePath, tryStatSync } from '../utils/index.js';

export function loadEnv(
Expand Down
83 changes: 38 additions & 45 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fs from 'node:fs';
import { createRequire } from 'node:module';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

import fse from 'fs-extra';

import { bindingPath } from '../../binding/index.js';
Expand Down Expand Up @@ -49,12 +50,15 @@ import merge from '../utils/merge.js';
import {
CUSTOM_KEYS,
DEFAULT_CONFIG_NAMES,
ENV_DEVELOPMENT,
ENV_PRODUCTION,
FARM_DEFAULT_NAMESPACE
} from './constants.js';
import { mergeConfig, mergeFarmCliConfig } from './mergeConfig.js';

import { normalizeCss } from './normalize-config/normalize-css.js';
import { normalizeExternal } from './normalize-config/normalize-external.js';
import normalizePartialBundling from './normalize-config/normalize-partial-bundling.js';
import { normalizePartialBundling } from './normalize-config/normalize-partial-bundling.js';
import { normalizeResolve } from './normalize-config/normalize-resolve.js';

import type { OutputConfig } from '../types/binding.js';
Expand Down Expand Up @@ -289,8 +293,8 @@ export async function normalizeUserCompilationConfig(
compilation
);

const isProduction = mode === 'production';
const isDevelopment = mode === 'development';
const isProduction = mode === ENV_PRODUCTION;
const isDevelopment = mode === ENV_DEVELOPMENT;
resolvedCompilation.mode = resolvedCompilation.mode ?? mode;

resolvedCompilation.coreLibPath = bindingPath;
Expand Down Expand Up @@ -342,52 +346,32 @@ export async function normalizeUserCompilationConfig(

const require = createRequire(import.meta.url);
const hmrClientPluginPath = require.resolve('@farmfe/runtime-plugin-hmr');
const ImportMetaPluginPath = require.resolve(
const importMetaPluginPath = require.resolve(
'@farmfe/runtime-plugin-import-meta'
);

if (!resolvedCompilation.runtime) {
resolvedCompilation.runtime = {
path: require.resolve('@farmfe/runtime'),
plugins: []
};
}

if (!resolvedCompilation.runtime.path) {
resolvedCompilation.runtime.path = require.resolve('@farmfe/runtime');
}

if (!resolvedCompilation.runtime.swcHelpersPath) {
resolvedCompilation.runtime.swcHelpersPath = path.dirname(
require.resolve('@swc/helpers/package.json')
);
}
resolvedCompilation.runtime = {
path:
resolvedCompilation.runtime?.path ?? require.resolve('@farmfe/runtime'),
swcHelpersPath:
resolvedCompilation.runtime?.swcHelpersPath ??
path.dirname(require.resolve('@swc/helpers/package.json')),
plugins: resolvedCompilation.runtime?.plugins ?? [],
namespace: resolvedCompilation.runtime?.namespace
};

if (!resolvedCompilation.runtime.plugins) {
resolvedCompilation.runtime.plugins = [];
} else {
const resolvePluginPath = (plugin: any) => {
resolvedCompilation.runtime.plugins = resolvedCompilation.runtime.plugins.map(
(plugin) => {
if (path.isAbsolute(plugin)) return plugin;
return plugin.startsWith('.')
? path.resolve(resolvedRootPath, plugin)
: require.resolve(plugin);
};
// make sure all plugin paths are absolute
resolvedCompilation.runtime.plugins =
resolvedCompilation.runtime.plugins.map(resolvePluginPath);
}
// set namespace to package.json name field's hash
if (!resolvedCompilation.runtime.namespace) {
// read package.json name field
const packageJsonPath = path.resolve(resolvedRootPath, 'package.json');
const packageJsonExists = fse.existsSync(packageJsonPath);
const namespaceName = packageJsonExists
? JSON.parse(fse.readFileSync(packageJsonPath, 'utf-8')).name ||
FARM_DEFAULT_NAMESPACE
: FARM_DEFAULT_NAMESPACE;
}
);

if (!resolvedCompilation.runtime.namespace) {
resolvedCompilation.runtime.namespace = createHash('md5')
.update(namespaceName)
.update(getNamespaceName(resolvedRootPath))
.digest('hex');
}

Expand Down Expand Up @@ -440,9 +424,9 @@ export async function normalizeUserCompilationConfig(

if (
isArray(resolvedCompilation.runtime.plugins) &&
!resolvedCompilation.runtime.plugins.includes(ImportMetaPluginPath)
!resolvedCompilation.runtime.plugins.includes(importMetaPluginPath)
) {
resolvedCompilation.runtime.plugins.push(ImportMetaPluginPath);
resolvedCompilation.runtime.plugins.push(importMetaPluginPath);
}

// we should not deep merge compilation.input
Expand Down Expand Up @@ -818,7 +802,7 @@ export async function loadConfigFile(
const errorMessage = convertErrorMessage(error);
const stackTrace =
error.code === 'GenericFailure' ? '' : `\n${error.stack}`;
if (inlineOptions.mode === 'production') {
if (inlineOptions.mode === ENV_PRODUCTION) {
throw new Error(
`Failed to load farm config file: ${errorMessage} \n${stackTrace}`
);
Expand Down Expand Up @@ -951,7 +935,7 @@ export async function resolveDefaultUserConfig(options: any) {

const normalizedConfig = await normalizeUserCompilationConfig(
resolvedUserConfig,
'development'
options.mode
);

return normalizedConfig;
Expand Down Expand Up @@ -999,8 +983,8 @@ export async function resolveUserConfig(
// TODO publicPath rewrite to BASE_URL
BASE_URL: userConfig.compilation.output.publicPath ?? '/',
mode: userConfig.mode,
DEV: userConfig.compilation.mode === 'development',
PROD: userConfig.compilation.mode === 'production'
DEV: userConfig.compilation.mode === ENV_DEVELOPMENT,
PROD: userConfig.compilation.mode === ENV_PRODUCTION
};

resolvedUserConfig.publicDir = normalizePublicDir(
Expand Down Expand Up @@ -1116,3 +1100,12 @@ async function setLazyCompilationDefine(
}://${hostname.host || 'localhost'}:${resolvedUserConfig.server.port}`
};
}

function getNamespaceName(rootPath: string) {
const packageJsonPath = path.resolve(rootPath, 'package.json');
if (fse.existsSync(packageJsonPath)) {
const { name } = JSON.parse(fse.readFileSync(packageJsonPath, 'utf-8'));
return name || FARM_DEFAULT_NAMESPACE;
}
return FARM_DEFAULT_NAMESPACE;
}
1 change: 1 addition & 0 deletions packages/core/src/config/mergeConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path, { isAbsolute } from 'node:path';

import { isString } from '../plugin/js/utils.js';
import { isArray, isObject } from '../utils/share.js';
import { CompilationMode } from './env.js';
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/config/normalize-config/normalize-asset.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CUSTOM_KEYS } from '../constants.js';
import { ResolvedCompilation, UserConfig } from '../types.js';

import type { ResolvedCompilation, UserConfig } from '../types.js';

export function normalizeAsset(
config: UserConfig,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/config/normalize-config/normalize-css.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CUSTOM_KEYS } from '../constants.js';
import { ResolvedCompilation, UserConfig } from '../types.js';

import type { ResolvedCompilation, UserConfig } from '../types.js';
export function normalizeCss(
config: UserConfig,
resolvedCompilation: ResolvedCompilation
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import module from 'node:module';

import { existsSync, readFileSync } from 'node:fs';
import module from 'node:module';
import path from 'node:path';

import { Config } from '../../types/binding.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path, { isAbsolute } from 'node:path';

import { browsersWithSupportForFeatures } from 'farm-browserslist-generator';

import path, { isAbsolute } from 'node:path';
import { Config } from '../../types/binding.js';
import { urlRegex } from '../../utils/http.js';
import { Logger } from '../../utils/logger.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CUSTOM_KEYS } from '../constants.js';
import { ResolvedCompilation } from '../types.js';

export default function normalizePartialBundling(
import type { ResolvedCompilation } from '../types.js';

export function normalizePartialBundling(
resolvedCompilation: ResolvedCompilation
) {
const partialBundlingItemEnforceMap: Record<string, boolean> = {};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CUSTOM_KEYS } from '../constants.js';
import { ResolvedCompilation, UserConfig } from '../types.js';

import type { ResolvedCompilation, UserConfig } from '../types.js';

export function normalizeResolve(
config: UserConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/config/schema.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import http from 'node:http';
import type { OutgoingHttpHeaders, SecureServerOptions } from 'node:http2';

import { z } from 'zod';
import { fromZodError } from 'zod-validation-error';

import { Logger } from '../utils/logger.js';

import type { OutgoingHttpHeaders, SecureServerOptions } from 'node:http2';
import type { UserConfig } from './types.js';

enum TargetEnv {
Expand Down
Loading

0 comments on commit 4b27ff7

Please sign in to comment.