Skip to content

Commit

Permalink
refactor: optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
ClarkXia committed Aug 18, 2023
1 parent d32b9c3 commit e01fa3e
Show file tree
Hide file tree
Showing 74 changed files with 1,321 additions and 454 deletions.
2 changes: 2 additions & 0 deletions packages/ice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
"@ice/bundles": "0.1.12",
"@ice/route-manifest": "1.2.0",
"@ice/runtime": "^1.2.7",
"@ice/shared-config": "1.0.0",
"@ice/webpack-config": "1.0.19",
"@ice/rspack-config": "1.0.0",
"@swc/helpers": "0.5.1",
"@types/express": "^4.17.14",
"address": "^1.1.2",
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/bundler/config/getUrls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { TaskConfig } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type { AppConfig } from '@ice/runtime/types';
import type { Configuration as DevServerConfiguration } from 'webpack-dev-server';
import prepareURLs from '../../utils/prepareURLs.js';
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/bundler/config/middlewares.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Configuration as DevServerConfiguration } from 'webpack-dev-server';
import type { TaskConfig } from 'build-scripts';
import type { RenderMode } from '@ice/runtime';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import createMockMiddleware from '../../middlewares/mock/createMiddleware.js';
import createRenderMiddleware from '../../middlewares/renderMiddleware.js';
import type { UserConfig } from '../../types/userConfig.js';
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion packages/ice/src/bundler/rspack/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { logger } from '../../utils/logger.js';
import { getOutputPaths, removeServerOutput } from '../config/outputPaths.js';
import { getOutputPaths, removeServerOutput } from '../config/output.js';
import type { BuildOptions, CompileResults, MultiStats } from '../types.js';
import formatStats from './formatStats.js';

Expand Down
217 changes: 46 additions & 171 deletions packages/ice/src/bundler/rspack/getConfig.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as path from 'path';
import { createRequire } from 'module';
import { compilationPlugin, compileExcludes } from '@ice/webpack-config';
import getRspackConfig from '@ice/rspack-config';
import type { Configuration } from '@rspack/core';
import type { Config } from '@ice/shared-config/types';
import { getRouteExportConfig } from '../../service/config.js';
import {
RUNTIME_TMP_DIR,
Expand All @@ -14,19 +13,12 @@ import { getReCompilePlugin, getServerPlugin, getSpinnerPlugin } from '../config
import { getExpandedEnvs } from '../../utils/runtimeEnv.js';
import DataLoaderPlugin from '../../webpack/DataLoaderPlugin.js';
import type { BundlerOptions, Context } from '../types.js';
import AssetManifest from './plugins/AssetManifest.js';
import getSplitChunks from './splitChunks.js';
import getDefine from './getDefine.js';
import getAssetsRule from './assetsRule.js';
import getCssRules from './cssRules.js';

type GetConfig = (
context: Context,
options: BundlerOptions
) => Promise<Configuration[]>;

const require = createRequire(import.meta.url);

const getConfig: GetConfig = async (context, options) => {
const {
taskConfigs,
Expand All @@ -47,170 +39,53 @@ const getConfig: GetConfig = async (context, options) => {
generator,
},
} = context;

return taskConfigs.map((taskConfig) => {
const {
mode,
publicPath = '/',
cacheDir,
outputDir,
sourceMap,
externals = {},
alias = {},
compileIncludes,
polyfill,
swcOptions,
hash,
define = {},
server,
splitChunks,
target,
enableRpx2Vw = true,
postcss,
proxy,
devServer = {},
useDataLoader,
} = taskConfig?.config || {};
const absoluteOutputDir = path.isAbsolute(outputDir) ? outputDir : path.join(rootDir, outputDir);
const hashKey = hash === true ? 'hash:8' : (hash || '');
const compilation = compilationPlugin({
const { reCompile, ensureRoutesConfig } = getRouteExportConfig(rootDir);
const getPlugins = (taskConfig: Config): Configuration['plugins'] => {
const { target, outputDir, useDataLoader, server } = taskConfig;
return [
// Add spinner for webpack task.
getSpinnerPlugin(spinner),
// Add Server runner plugin.
getServerPlugin({
serverRunner,
ensureRoutesConfig,
serverCompiler,
target,
rootDir,
serverEntry: server?.entry,
outputDir,
serverCompileTask,
userConfig,
}),
// Add ReCompile plugin when routes config changed.
getReCompilePlugin(reCompile, routeManifest),
// Add DataLoader plugin.
useDataLoader && new DataLoaderPlugin({
serverCompiler,
target,
rootDir,
getAllPlugin,
frameworkExports: generator.getExportList('framework', target),
}),
].filter(Boolean);
};
return taskConfigs.map(({ config }) => {
const plugins = getPlugins(config);
return getRspackConfig({
rootDir,
cacheDir,
sourceMap,
fastRefresh: false,
mode,
compileIncludes,
compileExcludes,
swcOptions,
polyfill,
enableEnv: true,
getRoutesFile,
});

const { reCompile, ensureRoutesConfig } = getRouteExportConfig(rootDir);
const cssFilename = `css/${hashKey ? `[name]-[${hashKey}].css` : '[name].css'}`;
const config: Configuration = {
entry: {
main: [path.join(rootDir, RUNTIME_TMP_DIR, 'entry.client.tsx')],
},
name: 'web',
mode,
externals,
output: {
clean: true,
publicPath,
path: absoluteOutputDir,
filename: `js/${hashKey ? `[name]-[${hashKey}].js` : '[name].js'}`,
cssFilename,
cssChunkFilename: cssFilename,
assetModuleFilename: 'assets/[name].[hash:8][ext]',
},
context: rootDir,
module: {
rules: [
// Compliation rules for js / ts.
{
test: compilation.transformInclude,
use: [{
loader: require.resolve('@ice/webpack-config/compilation-loader'),
options: {
transform: compilation.transform,
},
}],
},
...getAssetsRule(),
...getCssRules({
rootDir,
enableRpx2Vw,
postcssOptions: postcss,
}),
],
runtimeTmpDir: RUNTIME_TMP_DIR,
runtimeDefineVars: {
[IMPORT_META_TARGET]: JSON.stringify(config.target),
[IMPORT_META_RENDERER]: JSON.stringify('client'),
},
resolve: {
alias,
},
watchOptions: {
ignored: /node_modules/,
aggregateTimeout: 100,
},
optimization: {
splitChunks: typeof splitChunks == 'object'
? splitChunks
: getSplitChunks(rootDir, splitChunks),
},
plugins: [
new AssetManifest({
fileName: 'assets-manifest.json',
outputDir: path.join(rootDir, RUNTIME_TMP_DIR),
}),
// Add spinner for webpack task.
getSpinnerPlugin(spinner),
// Add Server runner plugin.
getServerPlugin({
serverRunner,
ensureRoutesConfig,
serverCompiler,
target,
rootDir,
serverEntry: server?.entry,
outputDir,
serverCompileTask,
userConfig,
}),
// Add ReCompile plugin when routes config changed.
getReCompilePlugin(reCompile, routeManifest),
// Add DataLoader plugin.
useDataLoader && new DataLoaderPlugin({
serverCompiler,
target,
rootDir,
getAllPlugin,
frameworkExports: generator.getExportList('framework', target),
}),
].filter(Boolean),
builtins: {
define: getDefine(define, {
[IMPORT_META_TARGET]: JSON.stringify(target),
[IMPORT_META_RENDERER]: JSON.stringify('client'),
}, getExpandedEnvs),
provide: {
process: [require.resolve('process/browser')],
$ReactRefreshRuntime$: [require.resolve('./client/reactRefresh.cjs')],
},
devFriendlySplitChunks: true,
css: {
modules: {
localIdentName: mode === 'development'
? CSS_MODULES_LOCAL_IDENT_NAME_DEV
: CSS_MODULES_LOCAL_IDENT_NAME,
},
},
},
stats: 'none',
infrastructureLogging: {
level: 'warn',
},
devServer: {
allowedHosts: 'all',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
},
// @ts-expect-error devServer.hot in rspack only support boolean.
hot: true,
compress: false,
proxy,
devMiddleware: {
publicPath,
},
client: {
logging: 'info',
},
...devServer,
getRoutesFile,
getExpandedEnvs,
localIdentName: config.mode === 'development' ? CSS_MODULES_LOCAL_IDENT_NAME_DEV : CSS_MODULES_LOCAL_IDENT_NAME,
taskConfig: {
...config,
plugins: (config.plugins || []).concat(plugins),
},
};
return config;
});
});
};

Expand Down
28 changes: 0 additions & 28 deletions packages/ice/src/bundler/rspack/getDefine.ts

This file was deleted.

3 changes: 1 addition & 2 deletions packages/ice/src/bundler/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type ora from '@ice/bundles/compiled/ora/index.js';
import type { Stats as WebpackStats } from '@ice/bundles/compiled/webpack/index.js';
import type { AppConfig } from '@ice/runtime/types';
Expand All @@ -21,7 +21,6 @@ export interface BuildOptions {
taskConfigs: BundlerOptions['taskConfigs'];
}


export interface BundlerOptions {
taskConfigs: TaskConfig<Config>[];
spinner: ora.Ora;
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/bundler/webpack/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type webpack from '@ice/bundles/compiled/webpack/index.js';
import type { StatsCompilation, StatsError, Configuration } from 'webpack';
import { getOutputPaths, removeServerOutput } from '../config/outputPaths.js';
import { getOutputPaths, removeServerOutput } from '../config/output.js';
import { logger } from '../../utils/logger.js';
import formatWebpackMessages from '../../utils/formatWebpackMessages.js';
import type { BundlerOptions, CompileResults, Context } from '../types.js';
Expand Down
2 changes: 2 additions & 0 deletions packages/ice/src/bundler/webpack/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export async function startDevServer(
a.split('/').filter(Boolean).length - b.split('/').filter(Boolean).length);
const webTaskConfig = taskConfigs.find(({ name }) => name === WEB);
const customMiddlewares = webpackConfigs[0].devServer?.setupMiddlewares;
// @ts-expect-error
const defaultDevServerConfig = await getDefaultServerConfig(webpackConfigs[0].devServer, commandArgs);
let devServerConfig: DevServerConfiguration = {
...defaultDevServerConfig,
Expand All @@ -46,6 +47,7 @@ export async function startDevServer(
mock: commandArgs.mock,
rootDir,
});
// @ts-expect-error
return customMiddlewares ? customMiddlewares(builtInMiddlewares, devServer) : builtInMiddlewares;
},
};
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/commands/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Context, TaskConfig } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type ora from '@ice/bundles/compiled/ora/index.js';

function test(
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createRequire } from 'module';
import trustCert from '@ice/bundles/compiled/trusted-cert/index.js';
import fse from 'fs-extra';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type { UserConfigContext } from 'build-scripts';
import lodash from '@ice/bundles/compiled/lodash/index.js';
import type { UserConfig } from './types/userConfig.js';
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/createService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { fileURLToPath } from 'url';
import { createRequire } from 'module';
import { Context } from 'build-scripts';
import type { CommandArgs, CommandName } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type { AppConfig } from '@ice/runtime/types';
import webpack from '@ice/bundles/compiled/webpack/index.js';
import type {
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/getWatchEvents.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path';
import type { Context } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type { WatchEvent } from './types/plugin.js';
import { generateRoutesInfo, getRoutesDefinition } from './routes.js';
import type Generator from './service/runtimeGenerator';
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/middlewares/renderMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ExpressRequestHandler, Middleware } from 'webpack-dev-server';
import type { ServerContext, RenderMode } from '@ice/runtime';
import matchRoutes from '@ice/runtime/matchRoutes';
import type { TaskConfig } from 'build-scripts';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import type { ExtendsPluginAPI } from '../types/plugin.js';
import getRouterBasename from '../utils/getRouterBasename.js';
import warnOnHashRouterEnabled from '../utils/warnOnHashRouterEnabled.js';
Expand Down
2 changes: 1 addition & 1 deletion packages/ice/src/plugins/web/task.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as path from 'path';
import { createRequire } from 'module';
import type { Config } from '@ice/webpack-config/types';
import type { Config } from '@ice/shared-config/types';
import { CACHE_DIR, RUNTIME_TMP_DIR, WEB } from '../../constant.js';

const require = createRequire(import.meta.url);
Expand Down
Loading

0 comments on commit e01fa3e

Please sign in to comment.