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

feat: support apply environment html-related config #2647

Merged
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ exports[`applyDefaultPlugins > should apply default plugins correctly 1`] = `
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down Expand Up @@ -760,6 +761,7 @@ exports[`applyDefaultPlugins > should apply default plugins correctly when produ
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ exports[`webpackConfig > should allow to append and prepend plugins 1`] = `
"version": 5,
},
HtmlBasicPlugin {
"environment": "web",
"modifyTagsFn": [Function],
"name": "HtmlBasicPlugin",
"options": {
Expand Down
6 changes: 1 addition & 5 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ const createDefaultConfig = (): RsbuildConfig => ({
environments: {},
});

function getDefaultEntry(root: string): RsbuildEntry {
export function getDefaultEntry(root: string): RsbuildEntry {
const files = [
// Most projects are using typescript now.
// So we put `.ts` as the first one to improve performance.
Expand Down Expand Up @@ -215,10 +215,6 @@ export const withDefaultConfig = async (

merged.source ||= {};

if (!merged.source.entry) {
merged.source.entry = getDefaultEntry(rootPath);
}

if (!merged.source.tsconfigPath) {
const tsconfigPath = join(rootPath, TS_CONFIG_FILE);

Expand Down
20 changes: 20 additions & 0 deletions packages/core/src/createContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import {
DEFAULT_BROWSERSLIST,
type NormalizedEnvironmentConfig,
type RsbuildContext,
type RsbuildEntry,
getBrowserslist,
isHtmlDisabled,
} from '@rsbuild/shared';
import { withDefaultConfig } from './config';
import { ROOT_DIST_DIR } from './constants';
import { initHooks } from './initHooks';
import { getHTMLPathByEntry } from './initPlugins';
import { logger } from './logger';
import { getEntryObject } from './plugins/entry';
import type {
Expand Down Expand Up @@ -80,6 +83,19 @@ export async function getBrowserslistByEnvironment(
return DEFAULT_BROWSERSLIST[target];
}

const getEnvironmentHTMLPaths = (
entry: RsbuildEntry,
config: NormalizedEnvironmentConfig,
) => {
if (isHtmlDisabled(config, config.output.target)) {
return {};
}
return Object.keys(entry).reduce<Record<string, string>>((prev, key) => {
prev[key] = getHTMLPathByEntry(key, config);
return prev;
}, {});
};

export async function updateEnvironmentContext(
context: RsbuildContext,
configs: Record<string, NormalizedEnvironmentConfig>,
Expand All @@ -90,17 +106,21 @@ export async function updateEnvironmentContext(
const tsconfigPath = config.source.tsconfigPath
? getAbsolutePath(context.rootPath, config.source.tsconfigPath)
: undefined;
const entry = getEntryObject(config, config.output.target);

const browserslist = await getBrowserslistByEnvironment(
context.rootPath,
config,
);

const htmlPaths = getEnvironmentHTMLPaths(entry, config);

context.environments[name] = {
target: config.output.target,
distPath: getAbsoluteDistPath(context.rootPath, config),
entry: getEntryObject(config, config.output.target),
browserslist,
htmlPaths,
tsconfigPath,
};
}
Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/initPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { InternalContext, NormalizedConfig } from './types';

export function getHTMLPathByEntry(
entryName: string,
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
) {
const filename =
config.html.outputStructure === 'flat'
Expand Down Expand Up @@ -97,13 +97,13 @@ export function getPluginAPI({
throw new Error('`getRsbuildConfig` get an invalid type param.');
}) as GetRsbuildConfig;

const getHTMLPaths = () => {
return Object.keys(context.entry).reduce<Record<string, string>>(
(prev, key) => {
prev[key] = getHTMLPathByEntry(key, getNormalizedConfig());
return prev;
},
{},
const getHTMLPaths = (options?: { environment: string }) => {
if (options?.environment) {
return context.environments[options.environment].htmlPaths;
}
return Object.values(context.environments).reduce(
(prev, context) => Object.assign(prev, context.htmlPaths),
{} as Record<string, string>,
);
};

Expand Down
43 changes: 26 additions & 17 deletions packages/core/src/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {
HTMLPluginOptions,
HtmlConfig,
ModifyHTMLTagsFn,
NormalizedConfig,
NormalizedEnvironmentConfig,
RsbuildPluginAPI,
} from '@rsbuild/shared';
import type { EntryDescription } from '@rspack/core';
Expand All @@ -28,7 +28,7 @@ import { parseMinifyOptions } from './minimize';

function applyRemoveConsole(
options: MinifyJSOptions,
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
) {
const { removeConsole } = config.performance;
const compressOptions =
Expand All @@ -50,7 +50,7 @@ function applyRemoveConsole(
return options;
}

function getTerserMinifyOptions(config: NormalizedConfig) {
function getTerserMinifyOptions(config: NormalizedEnvironmentConfig) {
const options: MinifyJSOptions = {
mangle: {
safari10: true,
Expand All @@ -70,7 +70,7 @@ function getTerserMinifyOptions(config: NormalizedConfig) {

export async function getHtmlMinifyOptions(
isProd: boolean,
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
) {
if (
!isProd ||
Expand Down Expand Up @@ -102,15 +102,21 @@ export async function getHtmlMinifyOptions(
: htmlMinifyDefaultOptions;
}

export function getTitle(entryName: string, config: NormalizedConfig) {
export function getTitle(
entryName: string,
config: NormalizedEnvironmentConfig,
) {
return reduceConfigsMergeContext({
initial: '',
config: config.html.title,
ctx: { entryName },
});
}

export function getInject(entryName: string, config: NormalizedConfig) {
export function getInject(
entryName: string,
config: NormalizedEnvironmentConfig,
) {
return reduceConfigsMergeContext({
initial: 'head',
config: config.html.inject,
Expand All @@ -122,7 +128,7 @@ const existTemplatePath: string[] = [];

export async function getTemplate(
entryName: string,
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
rootPath: string,
): Promise<{ templatePath: string; templateContent?: string }> {
const DEFAULT_TEMPLATE = path.resolve(STATIC_PATH, 'template.html');
Expand Down Expand Up @@ -201,7 +207,7 @@ export function getMetaTags(

function getTemplateParameters(
entryName: string,
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
assetPrefix: string,
): HTMLPluginOptions['templateParameters'] {
return (compilation, assets, assetTags, pluginOptions) => {
Expand Down Expand Up @@ -252,8 +258,11 @@ function getChunks(
return chunks;
}

const getTagConfig = (api: RsbuildPluginAPI): TagConfig | undefined => {
const config = api.getNormalizedConfig();
const getTagConfig = (
api: RsbuildPluginAPI,
environment: string,
): TagConfig | undefined => {
const config = api.getNormalizedConfig({ environment });
const tags = castArray(config.html.tags).filter(Boolean);

// skip if options is empty.
Expand All @@ -274,8 +283,8 @@ export const pluginHtml = (modifyTagsFn?: ModifyHTMLTagsFn): RsbuildPlugin => ({

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

// if html is disabled or target is server, skip html plugin
if (isHtmlDisabled(config, target)) {
Expand All @@ -286,7 +295,7 @@ export const pluginHtml = (modifyTagsFn?: ModifyHTMLTagsFn): RsbuildPlugin => ({
const assetPrefix = getPublicPathFromChain(chain, false);
const entries = chain.entryPoints.entries() || {};
const entryNames = Object.keys(entries);
const htmlPaths = api.getHTMLPaths();
const htmlPaths = api.getHTMLPaths({ environment });
const htmlInfoMap: Record<string, HtmlInfo> = {};

const finalOptions = await Promise.all(
Expand Down Expand Up @@ -338,7 +347,7 @@ export const pluginHtml = (modifyTagsFn?: ModifyHTMLTagsFn): RsbuildPlugin => ({
htmlInfo.templateContent = templateContent;
}

const tagConfig = getTagConfig(api);
const tagConfig = getTagConfig(api, environment);
if (tagConfig) {
htmlInfo.tagConfig = tagConfig;
}
Expand Down Expand Up @@ -379,7 +388,7 @@ export const pluginHtml = (modifyTagsFn?: ModifyHTMLTagsFn): RsbuildPlugin => ({

chain
.plugin(CHAIN_ID.PLUGIN.HTML_BASIC)
.use(HtmlBasicPlugin, [htmlInfoMap, modifyTagsFn]);
.use(HtmlBasicPlugin, [htmlInfoMap, environment, modifyTagsFn]);

if (config.html) {
const { appIcon, crossorigin } = config.html;
Expand Down Expand Up @@ -411,8 +420,8 @@ export const pluginHtml = (modifyTagsFn?: ModifyHTMLTagsFn): RsbuildPlugin => ({
api.modifyHTMLTags({
// ensure `crossorigin` and `nonce` can be applied to all tags
order: 'post',
handler: ({ headTags, bodyTags }) => {
const config = api.getNormalizedConfig();
handler: ({ headTags, bodyTags }, { environment }) => {
const config = api.getNormalizedConfig({ environment });
const { crossorigin } = config.html;
const allTags = [...headTags, ...bodyTags];

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/plugins/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export const pluginManifest = (): RsbuildPlugin => ({
name: 'rsbuild:manifest',

setup(api) {
api.modifyBundlerChain(async (chain, { CHAIN_ID }) => {
api.modifyBundlerChain(async (chain, { CHAIN_ID, environment }) => {
const {
output: { manifest },
} = api.getNormalizedConfig();
Expand All @@ -156,7 +156,7 @@ export const pluginManifest = (): RsbuildPlugin => ({
typeof manifest === 'string' ? manifest : 'manifest.json';

const { RspackManifestPlugin } = await import('rspack-manifest-plugin');
const htmlPaths = api.getHTMLPaths();
const htmlPaths = api.getHTMLPaths({ environment });

chain.plugin(CHAIN_ID.PLUGIN.MANIFEST).use(RspackManifestPlugin, [
{
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/plugins/minimize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
CHAIN_ID,
type HTMLPluginOptions,
type NormalizedConfig,
type NormalizedEnvironmentConfig,
deepmerge,
isObject,
} from '@rsbuild/shared';
Expand Down Expand Up @@ -58,7 +59,7 @@ export const getSwcMinimizerOptions = (
};

export const parseMinifyOptions = (
config: NormalizedConfig,
config: NormalizedEnvironmentConfig,
isProd = true,
): {
minifyJs: boolean;
Expand Down
28 changes: 21 additions & 7 deletions packages/core/src/provider/initConfigs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
PluginManager,
RspackConfig,
} from '@rsbuild/shared';
import { normalizeConfig } from '../config';
import { getDefaultEntry, normalizeConfig } from '../config';
import {
updateContextByNormalizedConfig,
updateEnvironmentContext,
Expand Down Expand Up @@ -40,28 +40,39 @@ export type InitConfigsOptions = {

const normalizeEnvironmentsConfigs = (
normalizedConfig: NormalizedConfig,
rootPath: string,
): Record<string, NormalizedEnvironmentConfig> => {
const { environments, dev, server, provider, ...rsbuildSharedConfig } =
normalizedConfig;
if (environments && Object.keys(environments).length) {
return Object.fromEntries(
Object.entries(environments).map(([name, config]) => [
name,
{
Object.entries(environments).map(([name, config]) => {
const environmentConfig = {
...mergeRsbuildConfig(
rsbuildSharedConfig,
config as unknown as NormalizedEnvironmentConfig,
),
dev,
server,
},
]),
};

if (!environmentConfig.source.entry) {
// @ts-expect-error
chenjiahan marked this conversation as resolved.
Show resolved Hide resolved
environmentConfig.source.entry = getDefaultEntry(rootPath);
}

return [name, environmentConfig];
}),
);
}

return {
[camelCase(rsbuildSharedConfig.output.target)]: {
...rsbuildSharedConfig,
source: {
...rsbuildSharedConfig.source,
entry: rsbuildSharedConfig.source.entry ?? getDefaultEntry(rootPath),
9aoy marked this conversation as resolved.
Show resolved Hide resolved
},
dev,
server,
},
Expand All @@ -88,7 +99,10 @@ export async function initRsbuildConfig({
await modifyRsbuildConfig(context);
const normalizeBaseConfig = normalizeConfig(context.config);

const environments = normalizeEnvironmentsConfigs(normalizeBaseConfig);
const environments = normalizeEnvironmentsConfigs(
normalizeBaseConfig,
context.rootPath,
);

context.normalizedConfig = {
...normalizeBaseConfig,
Expand Down
Loading
Loading