Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
SoonIter committed Dec 24, 2024
1 parent ac486b9 commit 962c743
Show file tree
Hide file tree
Showing 15 changed files with 192 additions and 177 deletions.
5 changes: 4 additions & 1 deletion examples/react-component-bundle-false/rslib.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { type LibConfig, defineConfig } from '@rslib/core';
export default defineConfig({
source: {
entry: {
index: ['./src/**', '!./src/env.d.ts'],
index: [
'./src/**',
'!./src/env.d.ts'
],
},
},
lib: [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.button {
background: yellow;
background: url('../../assets/logo.svg') no-repeat;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import styles from './index.module.scss';
import logo from '../../assets/logo.svg'

interface CounterButtonProps {
onClick: () => void;
Expand All @@ -11,6 +12,7 @@ export const CounterButton: React.FC<CounterButtonProps> = ({
label,
}) => (
<button type="button" className={styles.button} onClick={onClick}>
<img src={logo} alt='react'/>
{label}
</button>
);
5 changes: 5 additions & 0 deletions examples/react-component-bundle-false/src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@ declare module '*.module.scss' {
const classes: { [key: string]: string };
export default classes;
}

declare module '*.svg' {
const url: string;
export default url;
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.button {
background: yellow;
background: url('../../assets/logo.svg') no-repeat;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import styles from './index.module.scss';
import logo from '../../assets/logo.svg'

interface CounterButtonProps {
onClick: () => void;
Expand All @@ -11,6 +12,7 @@ export const CounterButton: React.FC<CounterButtonProps> = ({
label,
}) => (
<button type="button" className={styles.button} onClick={onClick}>
<img src={logo} alt='react'/>
{label}
</button>
);
5 changes: 5 additions & 0 deletions examples/react-component-bundle/src/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@ declare module '*.module.scss' {
const classes: { [key: string]: string };
export default classes;
}

declare module '*.svg' {
const url: string;
export default url;
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@
},
"pnpm": {
"overrides": {
"zx>@types/node": "-"
"zx>@types/node": "-",
"@rspack/core": "/Users/bytedance/Documents/codes/rspack/packages/rspack"
}
}
}
74 changes: 74 additions & 0 deletions packages/core/src/asset/LibAssetExtractPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { type Rspack, rspack } from '@rsbuild/core';
import { getUndoPath } from '../css/utils';

type Options = {
}
/**
* these codes is written according to
* https://github.com/web-infra-dev/rspack/blob/61f0cd2b4e313445a9d3329ca71240e99edfb352/crates/rspack_plugin_asset/src/lib.rs#L531
*/
const pattern: RegExp = /__webpack_require__\.p\s\+\s["'](.+)["']/g;
function extractAssetFilenames (content: string): string[] {
console.log([...content.matchAll(pattern)])
return [...content.matchAll(pattern)].map(i => {
return i?.[1]
}).filter(Boolean) as string[];
}

const RSLIB_NAMESPACE_OBJECT = `__rslib_asset__`;

const esmSingleFileTemplate = (url: string) => `import ${RSLIB_NAMESPACE_OBJECT} from '${url}';
export default ${RSLIB_NAMESPACE_OBJECT};`;

const cjsSingleFileTemplate = (url: string) => `module.exports = require('${url}');`;

const pluginName = 'LIB_ASSET_EXTRACT_PLUGIN';

class LibAssetExtractPlugin implements Rspack.RspackPluginInstance {
readonly name: string = pluginName;
options: Options;
constructor(options?: Options) {
this.options = options ?? {};
}

apply(compiler: Rspack.Compiler): void {
compiler.hooks.make.tap(pluginName, (compilation) => {
compilation.hooks.processAssets.tap(pluginName, (assets) => {
const chunkAsset = Object.keys(assets).filter((name) =>
/js/.test(name),
);
for (const name of chunkAsset) {
const isEsmFormat = compilation.options.output.module;
const undoPath = getUndoPath(
name,
compilation.outputOptions.path!,
true,
);
compilation.updateAsset(name, (old) => {
const oldSource = old.source().toString();
const assetFilenames = extractAssetFilenames(oldSource);

if (assetFilenames.length === 1) {
const assetFilename = assetFilenames[0];
let newSource: string = '';
const url = `${undoPath}${assetFilename}`;

if(isEsmFormat) {
newSource = esmSingleFileTemplate(url);
} else {
newSource = cjsSingleFileTemplate(url);
}
return new rspack.sources.RawSource(newSource);
} else {
const newSource = new rspack.sources.ReplaceSource(old);
assetFilenames.forEach(() => {
})
return newSource;
}

});
}
})
})}
}
export { LibAssetExtractPlugin};
19 changes: 16 additions & 3 deletions packages/core/src/asset/assetConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RsbuildConfig } from '@rsbuild/core';
import type { Format } from '../types';
import { LibAssetExtractPlugin } from './LibAssetExtractPlugin';

// TODO: asset config document
export const composeAssetConfig = (
Expand All @@ -11,15 +12,27 @@ export const composeAssetConfig = (
return {
output: {
dataUriLimit: 0, // default: no inline asset
// assetPrefix: 'auto', // TODO: will turn on this with js support together in the future
assetPrefix: 'auto', // TODO: will turn on this with js support together in the future
},
tools: {
rspack: {
plugins: [new LibAssetExtractPlugin()]

},
},
};
}

// TODO: bundleless
return {
output: {
dataUriLimit: 0, // default: no inline asset
// assetPrefix: 'auto', // TODO: will turn on this with js support together in the future
assetPrefix: 'auto',
},
tools: {
rspack: {
plugins: [new LibAssetExtractPlugin()]

},
},
};
}
Expand Down
30 changes: 30 additions & 0 deletions packages/core/src/asset/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
const reRegExpChar: RegExp = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar: RegExp = RegExp(reRegExpChar.source);

/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string: string): string {
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}


export {escapeRegExp}
16 changes: 12 additions & 4 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -909,9 +909,12 @@ const composeEntryConfig = async (
});

// Filter the glob resolved entry files based on the allowed extensions
const resolvedEntryFiles = globEntryFiles.filter((file) =>
ENTRY_EXTENSIONS_PATTERN.test(file),
);
const resolvedEntryFiles = globEntryFiles;
ENTRY_EXTENSIONS_PATTERN;

// .filter((file) =>
// ENTRY_EXTENSIONS_PATTERN.test(file),
// );

if (resolvedEntryFiles.length === 0) {
throw new Error(`Cannot find ${resolvedEntryFiles}`);
Expand Down Expand Up @@ -1006,6 +1009,7 @@ const composeBundlelessExternalConfig = (
jsExtension,
cssModulesAuto,
isStyleRedirected,
contextInfo.issuer,
);

if (cssExternal !== false) {
Expand Down Expand Up @@ -1053,7 +1057,11 @@ const composeBundlelessExternalConfig = (
);
} else {
// If it does not match jsExtensionsPattern, we should do nothing, eg: ./foo.png
return callback();
resolvedRequest = resolvedRequest.replace(
/\.[^.]+$/,
jsExtension,
);
// return callback();
}
} else {
resolvedRequest = `${resolvedRequest}${jsExtension}`;
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/css/LibCssExtractPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { RSLIB_CSS_ENTRY_FLAG } from './cssConfig';
import {
ABSOLUTE_PUBLIC_PATH,
AUTO_PUBLIC_PATH,
BASE_URI,
SINGLE_DOT_PATH_SEGMENT,
} from './libCssExtractLoader';
import { getUndoPath } from './utils';
Expand Down Expand Up @@ -62,14 +63,15 @@ class LibCssExtractPlugin implements Rspack.RspackPluginInstance {
}
}

replace(ABSOLUTE_PUBLIC_PATH, '');
replace(SINGLE_DOT_PATH_SEGMENT, '.');
const undoPath = getUndoPath(
name,
compilation.outputOptions.path!,
false,
);
replace(AUTO_PUBLIC_PATH, undoPath);
replace(`${ABSOLUTE_PUBLIC_PATH}${AUTO_PUBLIC_PATH}`, undoPath);
replace(ABSOLUTE_PUBLIC_PATH, '');
replace(`${BASE_URI}/`, '');

return replaceSource;
});
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/css/cssConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,19 @@ export function cssExternalHandler(
jsExtension: string,
auto: CssLoaderOptionsAuto,
isStyleRedirect: boolean,
issuer: string,
): void | false {
const isCssModulesRequest = isCssModulesFile(request, auto);

// cssExtract would execute the file handled by css-loader, so we cannot external the "helper import" from css-loader
// do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
// 1. do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
if (/compiled\/css-loader\//.test(request)) {
return callback();
}
// 2.
if (isCssFile(issuer) && !isCssFile(request)) {
return callback();
}

// 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
// 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
Expand Down
Loading

0 comments on commit 962c743

Please sign in to comment.