Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 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
1 change: 1 addition & 0 deletions packages/core/rslib.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default defineConfig({
entry: {
index: './src/index.ts',
libCssExtractLoader: './src/css/libCssExtractLoader.ts',
entryModuleLoader: './src/plugins/entryModuleLoader.ts',
},
define: {
RSLIB_VERSION: JSON.stringify(require('./package.json').version),
Expand Down
46 changes: 37 additions & 9 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
DEFAULT_CONFIG_NAME,
ENTRY_EXTENSIONS_PATTERN,
JS_EXTENSIONS_PATTERN,
RSLIB_ENTRY_QUERY,
SWC_HELPERS,
} from './constant';
import {
Expand All @@ -23,6 +24,7 @@ import {
cssExternalHandler,
isCssGlobalFile,
} from './css/cssConfig';
import { composeEntryChunkConfig } from './plugins/EntryChunkPlugin';
import {
pluginCjsImportMetaUrlShim,
pluginEsmRequireShim,
Expand Down Expand Up @@ -598,7 +600,10 @@ const composeFormatConfig = ({
}
};

const composeShimsConfig = (format: Format, shims?: Shims): RsbuildConfig => {
const composeShimsConfig = (
format: Format,
shims?: Shims,
): { rsbuildConfig: RsbuildConfig; resolvedShims: Shims } => {
const resolvedShims = {
cjs: {
'import.meta.url': shims?.cjs?.['import.meta.url'] ?? true,
Expand All @@ -610,9 +615,10 @@ const composeShimsConfig = (format: Format, shims?: Shims): RsbuildConfig => {
},
};

let rsbuildConfig: RsbuildConfig = {};
switch (format) {
case 'esm':
return {
case 'esm': {
rsbuildConfig = {
tools: {
rspack: {
node: {
Expand All @@ -626,19 +632,23 @@ const composeShimsConfig = (format: Format, shims?: Shims): RsbuildConfig => {
Boolean,
),
};
break;
}
case 'cjs':
return {
rsbuildConfig = {
plugins: [
resolvedShims.cjs['import.meta.url'] && pluginCjsImportMetaUrlShim(),
].filter(Boolean),
};
break;
case 'umd':
return {};
case 'mf':
return {};
break;
default:
throw new Error(`Unsupported format: ${format}`);
}

return { rsbuildConfig, resolvedShims };
};

export const composeModuleImportWarn = (request: string): string => {
Expand Down Expand Up @@ -746,6 +756,16 @@ const composeSyntaxConfig = (
};
};

const appendEntryQuery = (
entry: NonNullable<RsbuildConfig['source']>['entry'],
): NonNullable<RsbuildConfig['source']>['entry'] => {
const newEntry: Record<string, string> = {};
for (const key in entry) {
newEntry[key] = `${entry[key]}?${RSLIB_ENTRY_QUERY}`;
}
return newEntry;
};

const composeEntryConfig = async (
entries: NonNullable<RsbuildConfig['source']>['entry'],
bundle: LibConfig['bundle'],
Expand All @@ -760,7 +780,7 @@ const composeEntryConfig = async (
return {
entryConfig: {
source: {
entry: entries,
entry: appendEntryQuery(entries),
},
},
lcp: null,
Expand Down Expand Up @@ -836,7 +856,7 @@ const composeEntryConfig = async (
const lcp = await calcLongestCommonPath(Object.values(resolvedEntries));
const entryConfig: RsbuildConfig = {
source: {
entry: resolvedEntries,
entry: appendEntryQuery(resolvedEntries),
},
};

Expand Down Expand Up @@ -1057,7 +1077,10 @@ async function composeLibRsbuildConfig(config: LibConfig, configPath: string) {
redirect = {},
umdName,
} = config;
const shimsConfig = composeShimsConfig(format!, shims);
const { rsbuildConfig: shimsConfig, resolvedShims } = composeShimsConfig(
format!,
shims,
);
const formatConfig = composeFormatConfig({
format: format!,
pkgJson: pkgJson!,
Expand Down Expand Up @@ -1100,6 +1123,10 @@ async function composeLibRsbuildConfig(config: LibConfig, configPath: string) {
cssModulesAuto,
);
const cssConfig = composeCssConfig(lcp, config.bundle);
const entryChunkConfig = composeEntryChunkConfig({
enabledImportMetaUrlShim:
format === 'cjs' && !!resolvedShims?.cjs?.['import.meta.url'],
});
const dtsConfig = await composeDtsConfig(config, dtsExtension);
const externalsWarnConfig = composeExternalsWarnConfig(
format!,
Expand Down Expand Up @@ -1127,6 +1154,7 @@ async function composeLibRsbuildConfig(config: LibConfig, configPath: string) {
targetConfig,
entryConfig,
cssConfig,
entryChunkConfig,
minifyConfig,
dtsConfig,
bannerFooterConfig,
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ export const DEFAULT_CONFIG_EXTENSIONS = [
] as const;

export const SWC_HELPERS = '@swc/helpers';
export const RSLIB_ENTRY_QUERY = '__rslib_entry__';
export const SHEBANG_PREFIX = '#!';
export const SHEBANG_REGEX: RegExp = /#!.*[\s\n\r]*$/;
export const REACT_DIRECTIVE_REGEX: RegExp =
/^['"]use (client|server)['"](;?)[\s\n\r]*$/;

export const JS_EXTENSIONS: string[] = [
'js',
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/css/RemoveCssExtractAssetPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const pluginName = 'REMOVE_CSS_EXTRACT_ASSET_PLUGIN';
type Options = {
include: RegExp;
};

class RemoveCssExtractAssetPlugin implements RspackPluginInstance {
readonly name: string = pluginName;
options: Options;
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/css/cssConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,10 @@ export function cssExternalHandler(
return false;
}

const pluginName = 'rsbuild:lib-css';
const PLUGIN_NAME = 'rsbuild:lib-css';

const pluginLibCss = (rootDir: string): RsbuildPlugin => ({
name: pluginName,
name: PLUGIN_NAME,
setup(api) {
api.modifyBundlerChain((config, { CHAIN_ID }) => {
let isUsingCssExtract = false;
Expand Down
210 changes: 210 additions & 0 deletions packages/core/src/plugins/EntryChunkPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import { chmodSync } from 'node:fs';
import { createRequire } from 'node:module';
import {
type RsbuildConfig,
type RsbuildPlugin,
type Rspack,
rspack,
} from '@rsbuild/core';
import {
JS_EXTENSIONS_PATTERN,
REACT_DIRECTIVE_REGEX,
SHEBANG_PREFIX,
SHEBANG_REGEX,
} from '../constant';
import { importMetaUrlShim } from './shims';
const require = createRequire(import.meta.url);

const PLUGIN_NAME = 'rsbuild:lib-entry-chunk';
const LOADER_NAME = 'rsbuild:lib-entry-module';

const matchFirstLine = (source: string, regex: RegExp): string | false => {
const lineBreakPos = source.match(/(\r\n|\n)/);
const firstLineContent = source.slice(0, lineBreakPos?.index);
const matched = regex.exec(firstLineContent);
if (!matched) {
return false;
}

return matched[0];
};

class EntryChunkPlugin {
private reactDirectives: Record<string, string> = {};

private shebangChmod = 0o755;
private shebangEntries: Record<string, string> = {};
private shebangInjectedAssets: Set<string> = new Set();

private enabledImportMetaUrlShim: boolean;

constructor({
enabledImportMetaUrlShim = true,
}: {
enabledImportMetaUrlShim: boolean;
}) {
this.enabledImportMetaUrlShim = enabledImportMetaUrlShim;
}

apply(compiler: Rspack.Compiler) {
compiler.hooks.entryOption.tap(PLUGIN_NAME, (_context, entries) => {
for (const name in entries) {
const entry = (entries as Rspack.EntryStaticNormalized)[name];
if (!entry) continue;

let first: string | undefined;
if (Array.isArray(entry)) {
first = entry[0];
} else if (Array.isArray(entry.import)) {
first = entry.import[0];
} else if (typeof entry === 'string') {
first = entry;
}

if (typeof first !== 'string') continue;

const filename = first.split('?')[0]!;
const isJs = JS_EXTENSIONS_PATTERN.test(filename);
if (!isJs) continue;

const content = compiler.inputFileSystem!.readFileSync!(filename, {
encoding: 'utf-8',
});

// Shebang
if (content.startsWith(SHEBANG_PREFIX)) {
const shebangMatch = matchFirstLine(content, SHEBANG_REGEX);
if (shebangMatch) {
this.shebangEntries[name] = shebangMatch;
}
}

// React directive
const reactDirective = matchFirstLine(content, REACT_DIRECTIVE_REGEX);
if (reactDirective) {
this.reactDirectives[name] = reactDirective;
}
}
});

compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.chunkAsset.tap(PLUGIN_NAME, (chunk, filename) => {
const isJs = JS_EXTENSIONS_PATTERN.test(filename);
if (!isJs) return;

const name = chunk.name;
if (!name) return;

const shebangEntry = this.shebangEntries[name];
if (shebangEntry) {
this.shebangEntries[filename] = shebangEntry;
}

const reactDirective = this.reactDirectives[name];
if (reactDirective) {
this.reactDirectives[filename] = reactDirective;
}
});
});

compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(PLUGIN_NAME, (assets) => {
if (!this.enabledImportMetaUrlShim) return;

const chunkAsset = Object.keys(assets).filter((name) =>
JS_EXTENSIONS_PATTERN.test(name),
);
for (const name of chunkAsset) {
compilation.updateAsset(name, (old) => {
const oldSource = old.source().toString();
const replaceSource = new rspack.sources.ReplaceSource(old);
if (
oldSource.startsWith('use strict;') ||
oldSource.startsWith('"use strict";')
) {
replaceSource.replace(
0,
11, // 'use strict;'.length,
`"use strict";\n${importMetaUrlShim}`,
);
} else {
replaceSource.insert(0, importMetaUrlShim);
}

return replaceSource;
});
}
});

compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
// Just after minify stage, to avoid from being minified.
stage: rspack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING - 1,
},
(assets) => {
const chunkAsset = Object.keys(assets);
for (const name of chunkAsset) {
const shebangValue = this.shebangEntries[name];
const reactDirectiveValue = this.reactDirectives[name];

if (shebangValue || reactDirectiveValue) {
compilation.updateAsset(name, (old) => {
const replaceSource = new rspack.sources.ReplaceSource(old);
// Shebang
if (shebangValue) {
replaceSource.insert(0, `${shebangValue}\n`);
this.shebangInjectedAssets.add(name);
}

// React directives
if (reactDirectiveValue) {
replaceSource.insert(0, `${reactDirectiveValue}\n`);
}

return replaceSource;
});
}
}
},
);
});

compiler.hooks.assetEmitted.tap(PLUGIN_NAME, (file, { targetPath }) => {
if (this.shebangInjectedAssets.has(file)) {
chmodSync(targetPath, this.shebangChmod);
}
});
}
}

const entryModuleLoaderRsbuildPlugin = (): RsbuildPlugin => ({
name: PLUGIN_NAME,
setup(api) {
api.modifyBundlerChain((config, { CHAIN_ID }) => {
config.module
.rule(CHAIN_ID.RULE.JS)
.use(LOADER_NAME)
.loader(require.resolve('./entryModuleLoader.js'));
});
},
});

export const composeEntryChunkConfig = ({
enabledImportMetaUrlShim,
}: {
enabledImportMetaUrlShim: boolean;
}): RsbuildConfig => {
return {
plugins: [entryModuleLoaderRsbuildPlugin()],
tools: {
rspack: {
plugins: [
new EntryChunkPlugin({
enabledImportMetaUrlShim,
}),
],
},
},
};
};
Loading
Loading