|
| 1 | +import { type Rspack, rspack } from '@rsbuild/core'; |
| 2 | +import { getUndoPath } from '../css/utils'; |
| 3 | + |
| 4 | +type Options = { |
| 5 | +} |
| 6 | +/** |
| 7 | + * these codes is written according to |
| 8 | + * https://github.com/web-infra-dev/rspack/blob/61f0cd2b4e313445a9d3329ca71240e99edfb352/crates/rspack_plugin_asset/src/lib.rs#L531 |
| 9 | + */ |
| 10 | +const pattern: RegExp = /__webpack_require__\.p\s\+\s["'](.+)["']/g; |
| 11 | +function extractAssetFilenames (content: string): string[] { |
| 12 | + console.log([...content.matchAll(pattern)]) |
| 13 | + return [...content.matchAll(pattern)].map(i => { |
| 14 | + return i?.[1] |
| 15 | + }).filter(Boolean) as string[]; |
| 16 | +} |
| 17 | + |
| 18 | +const RSLIB_NAMESPACE_OBJECT = `__rslib_asset__`; |
| 19 | + |
| 20 | +const esmSingleFileTemplate = (url: string) => `import ${RSLIB_NAMESPACE_OBJECT} from '${url}'; |
| 21 | +export default ${RSLIB_NAMESPACE_OBJECT};`; |
| 22 | + |
| 23 | +const cjsSingleFileTemplate = (url: string) => `module.exports = require('${url}');`; |
| 24 | + |
| 25 | +const pluginName = 'LIB_ASSET_EXTRACT_PLUGIN'; |
| 26 | + |
| 27 | +class LibAssetExtractPlugin implements Rspack.RspackPluginInstance { |
| 28 | + readonly name: string = pluginName; |
| 29 | + options: Options; |
| 30 | + constructor(options?: Options) { |
| 31 | + this.options = options ?? {}; |
| 32 | + } |
| 33 | + |
| 34 | + apply(compiler: Rspack.Compiler): void { |
| 35 | + compiler.hooks.make.tap(pluginName, (compilation) => { |
| 36 | + compilation.hooks.processAssets.tap(pluginName, (assets) => { |
| 37 | + const chunkAsset = Object.keys(assets).filter((name) => |
| 38 | + /js/.test(name), |
| 39 | + ); |
| 40 | + for (const name of chunkAsset) { |
| 41 | + const isEsmFormat = compilation.options.output.module; |
| 42 | + const undoPath = getUndoPath( |
| 43 | + name, |
| 44 | + compilation.outputOptions.path!, |
| 45 | + true, |
| 46 | + ); |
| 47 | + compilation.updateAsset(name, (old) => { |
| 48 | + const oldSource = old.source().toString(); |
| 49 | + const assetFilenames = extractAssetFilenames(oldSource); |
| 50 | + |
| 51 | + if (assetFilenames.length === 1) { |
| 52 | + const assetFilename = assetFilenames[0]; |
| 53 | + let newSource: string = ''; |
| 54 | + const url = `${undoPath}${assetFilename}`; |
| 55 | + |
| 56 | + if(isEsmFormat) { |
| 57 | + newSource = esmSingleFileTemplate(url); |
| 58 | + } else { |
| 59 | + newSource = cjsSingleFileTemplate(url); |
| 60 | + } |
| 61 | + return new rspack.sources.RawSource(newSource); |
| 62 | + } else { |
| 63 | + const newSource = new rspack.sources.ReplaceSource(old); |
| 64 | + assetFilenames.forEach(() => { |
| 65 | + }) |
| 66 | + return newSource; |
| 67 | + } |
| 68 | + |
| 69 | + }); |
| 70 | + } |
| 71 | + }) |
| 72 | +})} |
| 73 | +} |
| 74 | +export { LibAssetExtractPlugin}; |
0 commit comments