Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use environment param instead of context.environment #2721

Merged
merged 9 commits into from
Jun 28, 2024
8 changes: 4 additions & 4 deletions packages/compat/plugin-swc/src/minimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ export class SwcMinimizerPlugin {
constructor(options: {
jsMinify?: boolean | JsMinifyOptions;
cssMinify?: boolean | CssMinifyOptions;
rsbuildConfig: NormalizedEnvironmentConfig;
environmentConfig: NormalizedEnvironmentConfig;
}) {
this.minifyOptions = {
jsMinify: options.jsMinify
? deepmerge(
this.getDefaultJsMinifyOptions(options.rsbuildConfig),
this.getDefaultJsMinifyOptions(options.environmentConfig),
normalize(options.jsMinify, {}),
)
: undefined,
Expand All @@ -53,10 +53,10 @@ export class SwcMinimizerPlugin {
}

getDefaultJsMinifyOptions(
rsbuildConfig: NormalizedEnvironmentConfig,
environmentConfig: NormalizedEnvironmentConfig,
): JsMinifyOptions {
const options = {
...__internalHelper.getSwcMinimizerOptions(rsbuildConfig),
...__internalHelper.getSwcMinimizerOptions(environmentConfig),
mangle: true,
};

Expand Down
17 changes: 8 additions & 9 deletions packages/compat/plugin-swc/src/plugin.ts
9aoy marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,13 @@ export const pluginSwc = (options: PluginSwcOptions = {}): RsbuildPlugin => ({
order: 'pre',
handler: async (chain, utils) => {
const { CHAIN_ID, environment } = utils;
const rsbuildConfig = api.getNormalizedConfig({ environment });
const { config: environmentConfig, browserslist } = environment;
const { rootPath } = api.context;

const { browserslist } = api.context.environments[environment];
const swcConfigs = await applyPluginConfig(
options,
utils,
rsbuildConfig,
environmentConfig,
rootPath,
browserslist,
);
Expand All @@ -56,7 +55,7 @@ export const pluginSwc = (options: PluginSwcOptions = {}): RsbuildPlugin => ({
applyScriptCondition({
rule: chain.module.rule(CHAIN_ID.RULE.JS),
chain,
config: rsbuildConfig,
config: environmentConfig,
context: api.context,
includes: [],
excludes: [],
Expand Down Expand Up @@ -116,10 +115,10 @@ export const pluginSwc = (options: PluginSwcOptions = {}): RsbuildPlugin => ({
});

api.modifyBundlerChain((chain, { CHAIN_ID, isProd, environment }) => {
const rsbuildConfig = api.getNormalizedConfig({ environment });
const environmentConfig = environment.config;

if (checkUseMinify(mainConfig, rsbuildConfig, isProd)) {
const { minify } = rsbuildConfig.output;
if (checkUseMinify(mainConfig, environmentConfig, isProd)) {
const { minify } = environmentConfig.output;
const minifyJs =
minify === true || (typeof minify === 'object' && minify.js);
const minifyCss =
Expand All @@ -131,7 +130,7 @@ export const pluginSwc = (options: PluginSwcOptions = {}): RsbuildPlugin => ({
.use(SwcMinimizerPlugin, [
{
jsMinify: mainConfig.jsMinify ?? mainConfig.jsc?.minify ?? true,
rsbuildConfig,
environmentConfig,
},
]);
}
Expand All @@ -142,7 +141,7 @@ export const pluginSwc = (options: PluginSwcOptions = {}): RsbuildPlugin => ({
.use(SwcMinimizerPlugin, [
{
cssMinify: minifyCss ? mainConfig.cssMinify ?? true : false,
rsbuildConfig,
environmentConfig,
},
]);
}
Expand Down
7 changes: 6 additions & 1 deletion packages/compat/webpack/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,15 @@ export const build = async (
let isFirstCompile = true;
await context.hooks.onBeforeBuild.call({
bundlerConfigs: bundlerConfigs as RspackConfig[],
environments: context.environments,
});

const onDone = async (stats: Stats | MultiStats) => {
const p = context.hooks.onAfterBuild.call({ isFirstCompile, stats });
const p = context.hooks.onAfterBuild.call({
isFirstCompile,
stats,
environments: context.environments,
});
isFirstCompile = false;
await p;
};
Expand Down
1 change: 1 addition & 0 deletions packages/compat/webpack/src/createCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export async function createCompiler({

await context.hooks.onAfterCreateCompiler.call({
compiler,
environments: context.environments,
});
logger.debug('create compiler done');

Expand Down
5 changes: 2 additions & 3 deletions packages/compat/webpack/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ export const pluginAdaptor = (): RsbuildPlugin => ({

setup(api) {
api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, target }) => {
const config = api.getNormalizedConfig({ environment });
const { tsconfigPath } = api.context.environments[environment];
const { config, tsconfigPath } = environment;

if (tsconfigPath && config.source.aliasStrategy === 'prefer-tsconfig') {
await applyTsConfigPathsPlugin({
Expand All @@ -80,7 +79,7 @@ export const pluginAdaptor = (): RsbuildPlugin => ({
const { ProgressPlugin } = await import('./progress/ProgressPlugin');
chain.plugin(CHAIN_ID.PLUGIN.PROGRESS).use(ProgressPlugin, [
{
id: environment,
id: environment.name,
...(progress === true ? {} : progress),
},
]);
Expand Down
8 changes: 6 additions & 2 deletions packages/compat/webpack/src/webpackConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
reduceConfigsWithContext,
} from '@rsbuild/core';
import {
type EnvironmentContext,
type ModifyWebpackChainUtils,
type ModifyWebpackConfigUtils,
castArray,
Expand Down Expand Up @@ -68,7 +69,7 @@ async function modifyWebpackConfig(

async function getChainUtils(
target: RsbuildTarget,
environment: string,
environment: EnvironmentContext,
): Promise<ModifyWebpackChainUtils> {
const { default: webpack } = await import('webpack');
const nameMap = {
Expand Down Expand Up @@ -142,7 +143,10 @@ export async function generateWebpackConfig({
target: RsbuildTarget;
context: InternalContext;
}): Promise<WebpackConfig> {
const chainUtils = await getChainUtils(target, environment);
const chainUtils = await getChainUtils(
target,
context.environments[environment],
);
const { default: webpack } = await import('webpack');
const {
BannerPlugin,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ exports[`applyDefaultPlugins > should apply default plugins correctly 1`] = `
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"getEnvironment": [Function],
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down Expand Up @@ -761,7 +761,7 @@ exports[`applyDefaultPlugins > should apply default plugins correctly when produ
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"getEnvironment": [Function],
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ exports[`webpackConfig > should allow to append and prepend plugins 1`] = `
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"getEnvironment": [Function],
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down
14 changes: 9 additions & 5 deletions packages/core/src/createContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ async function createContextByConfig(

return {
version: RSBUILD_VERSION,
environments: {},
rootPath,
distPath: '',
cachePath,
Expand Down Expand Up @@ -129,12 +128,12 @@ const getEnvironmentHTMLPaths = (
};

export async function updateEnvironmentContext(
context: RsbuildContext,
context: InternalContext,
configs: Record<string, NormalizedEnvironmentConfig>,
): Promise<void> {
context.environments ||= {};

for (const [name, config] of Object.entries(configs)) {
for (const [index, [name, config]] of Object.entries(configs).entries()) {
const tsconfigPath = config.source.tsconfigPath
? getAbsolutePath(context.rootPath, config.source.tsconfigPath)
: undefined;
Expand All @@ -148,17 +147,21 @@ export async function updateEnvironmentContext(
const htmlPaths = getEnvironmentHTMLPaths(entry, config);

context.environments[name] = {
target: config.output.target,
index,
name,
distPath: getAbsoluteDistPath(context.rootPath, config),
entry,
browserslist,
htmlPaths,
tsconfigPath,
config,
};
}
}

export function updateContextByNormalizedConfig(context: RsbuildContext): void {
export function updateContextByNormalizedConfig(
context: InternalContext,
): void {
// Try to get the parent dist path from all environments
const distPaths = Object.values(context.environments).map(
(item) => item.distPath,
Expand Down Expand Up @@ -216,6 +219,7 @@ export async function createContext(

return {
...context,
environments: {},
hooks: initHooks(),
config: { ...rsbuildConfig },
originalConfig: userRsbuildConfig,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export type {
RsbuildEntry,
RsbuildTarget,
RsbuildContext,
EnvironmentContext,
InspectConfigResult,
InspectConfigOptions,
// Subtypes of Config
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export const pluginAsset = (): RsbuildPlugin => ({

setup(api) {
api.modifyBundlerChain((chain, { isProd, environment }) => {
const config = api.getNormalizedConfig({ environment });
const { config } = environment;

const createAssetRule = (
assetType: 'image' | 'media' | 'font' | 'svg',
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/plugins/basic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export const pluginBasic = (): RsbuildPlugin => ({
setup(api) {
api.modifyBundlerChain(
(chain, { env, isProd, target, bundler, environment, CHAIN_ID }) => {
const config = api.getNormalizedConfig({ environment });
const { config } = environment;

chain.name(environment);
chain.name(environment.name);

chain.devtool(getJsSourceMap(config));

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/plugins/bundleAnalyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function pluginBundleAnalyzer(): RsbuildPlugin {
});

api.modifyBundlerChain(async (chain, { CHAIN_ID, environment }) => {
const config = api.getNormalizedConfig({ environment });
const { config } = environment;

if (!isUseAnalyzer(config)) {
return;
Expand All @@ -58,7 +58,7 @@ export function pluginBundleAnalyzer(): RsbuildPlugin {
{
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: `report-${environment}.html`,
reportFilename: `report-${environment.name}.html`,
...(config.performance.bundleAnalyze || {}),
},
]);
Expand Down
16 changes: 10 additions & 6 deletions packages/core/src/plugins/cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import { isAbsolute, join } from 'node:path';
import type { BuildCacheOptions, RsbuildContext } from '@rsbuild/shared';
import type {
BuildCacheOptions,
EnvironmentContext,
RsbuildContext,
} from '@rsbuild/shared';
import { findExists, isFileExists } from '../helpers';
import type { NormalizedEnvironmentConfig, RsbuildPlugin } from '../types';

Expand Down Expand Up @@ -58,7 +62,7 @@ function getCacheDirectory(
async function getBuildDependencies(
context: Readonly<RsbuildContext>,
config: NormalizedEnvironmentConfig,
environment: string,
environmentContext: EnvironmentContext,
) {
const rootPackageJson = join(context.rootPath, 'package.json');
const browserslistConfig = join(context.rootPath, '.browserslistrc');
Expand All @@ -68,7 +72,7 @@ async function getBuildDependencies(
if (await isFileExists(rootPackageJson)) {
buildDependencies.packageJson = [rootPackageJson];
}
const { tsconfigPath } = context.environments[environment];
const { tsconfigPath } = environmentContext;

if (tsconfigPath) {
buildDependencies.tsconfig = [tsconfigPath];
Expand Down Expand Up @@ -105,7 +109,7 @@ export const pluginCache = (): RsbuildPlugin => ({
}

api.modifyBundlerChain(async (chain, { environment, env }) => {
const config = api.getNormalizedConfig({ environment });
const { config } = environment;
const { buildCache } = config.performance;

if (buildCache === false) {
Expand All @@ -132,8 +136,8 @@ export const pluginCache = (): RsbuildPlugin => ({
// The default cache name of webpack is '${name}-${env}', and the `name` is `default` by default.
// We set cache name to avoid cache conflicts of different targets.
name: useDigest
? `${environment}-${env}-${getDigestHash(cacheConfig.cacheDigest!)}`
: `${environment}-${env}`,
? `${environment.name}-${env}-${getDigestHash(cacheConfig.cacheDigest!)}`
: `${environment.name}-${env}`,
type: 'filesystem',
cacheDirectory,
buildDependencies,
Expand Down
27 changes: 11 additions & 16 deletions packages/core/src/plugins/cleanOutput.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { sep } from 'node:path';
import { color } from '@rsbuild/shared';
import { type EnvironmentContext, color } from '@rsbuild/shared';
import { emptyDir } from '../helpers';
import { logger } from '../logger';
import type { RsbuildPlugin } from '../types';
Expand All @@ -16,10 +16,9 @@ export const pluginCleanOutput = (): RsbuildPlugin => ({
name: 'rsbuild:clean-output',

setup(api) {
const clean = async (environment: string) => {
const clean = async (environment: EnvironmentContext) => {
const { rootPath } = api.context;
const config = api.getNormalizedConfig({ environment });
const { distPath } = api.context.environments[environment];
const { config, distPath } = environment;

let { cleanDistPath } = config.output;

Expand All @@ -44,23 +43,19 @@ export const pluginCleanOutput = (): RsbuildPlugin => ({
}
};

const cleanAll = async () => {
const distPaths = Object.entries(api.context.environments).reduce<
Array<{
environmentName: string;
distPath: string;
}>
>((total, [environmentName, curr]) => {
const cleanAll = async (params: {
environments: Record<string, EnvironmentContext>;
}) => {
const environments = Object.values(params.environments).reduce<
Array<EnvironmentContext>
>((total, curr) => {
if (!total.find((t) => t.distPath === curr.distPath)) {
total.push({
environmentName,
distPath: curr.distPath,
});
total.push(curr);
}
return total;
}, []);

await Promise.all(distPaths.map((d) => clean(d.environmentName)));
await Promise.all(environments.map((e) => clean(e)));
};

api.onBeforeBuild(cleanAll);
Expand Down
Loading
Loading