Skip to content

Commit

Permalink
Load webpack-sources as peer webpack to maintain compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
yoannmoinet committed Nov 2, 2024
1 parent 3642157 commit 2156afd
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 27 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"@rspack/core": "^1.0.14",
"@types/fs-extra": "^11.0.4",
"@types/node": "^22.8.1",
"@types/webpack-sources": "^3.2.3",
"bumpp": "^9.7.1",
"conventional-changelog-cli": "^5.0.0",
"esbuild": "^0.24.0",
Expand Down
47 changes: 33 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 14 additions & 13 deletions src/webpack/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,20 @@ export function contextOptionsFromCompilation(compilation: Compilation): Context
}
}

export function createBuildContext(options: ContextOptions, compiler: Compiler, compilation?: Compilation, loaderContext?: LoaderContext<{ unpluginName: string }>): UnpluginBuildContext {
const require = createRequire(import.meta.url)
const { sources } = require('webpack') as typeof import('webpack')
export function getSource(fileSource: string | Uint8Array) {
// Bypass yarn's pnp dependency verification
const webpackRequire = createRequire(require.resolve('webpack'))
const RawSource = (webpackRequire('webpack-sources') as typeof import('webpack-sources')).RawSource

return new RawSource(
typeof fileSource === 'string'
? fileSource
// Converting to string to support Webpack 4's RawSource.
: Buffer.from(fileSource.buffer).toString('utf-8'),
)
}

export function createBuildContext(options: ContextOptions, compiler: Compiler, compilation?: Compilation, loaderContext?: LoaderContext<{ unpluginName: string }>): UnpluginBuildContext {
return {
parse(code: string, opts: any = {}) {
return Parser.parse(code, {
Expand All @@ -45,16 +55,7 @@ export function createBuildContext(options: ContextOptions, compiler: Compiler,
throw new Error('unplugin/webpack: emitFile outside supported hooks (buildStart, buildEnd, load, transform, watchChange)')
compilation.emitAsset(
outFileName,
sources
? new sources.RawSource(
typeof emittedFile.source === 'string'
? emittedFile.source
: Buffer.from(emittedFile.source),
) as any
: {
source: () => emittedFile.source,
size: () => emittedFile.source!.length,
},
getSource(emittedFile.source) as import('webpack').sources.Source,
)
}
},
Expand Down

0 comments on commit 2156afd

Please sign in to comment.