Skip to content

Commit

Permalink
fix: support Source without #sourceAndMap()
Browse files Browse the repository at this point in the history
fix #298
  • Loading branch information
privatenumber committed Jan 13, 2023
1 parent 106484b commit f5bc714
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/minify-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,20 @@ class ESBuildMinifyPlugin {

await Promise.all(assets.map(async (asset) => {
const assetIsCss = isCssFile.test(asset.name);
const { source, map } = asset.source.sourceAndMap();
let source: string | Buffer | ArrayBuffer;
let map = null;

if (asset.source.sourceAndMap) {
const sourceAndMap = asset.source.sourceAndMap();
source = sourceAndMap.source;
map = sourceAndMap.map;
} else {
source = asset.source.source();
if (asset.source.map) {
map = asset.source.map();
}
}

const sourceAsString = source.toString();
const result = await this.transform(sourceAsString, {
...transformOptions,
Expand Down
38 changes: 38 additions & 0 deletions tests/specs/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,5 +550,43 @@ export default testSuite(({ describe }, webpack: typeof webpack4 | typeof webpac
expect(sourcemapFile).toMatch(/styles\.css/);
});
});

test('supports Source without #sourceAndMap()', async () => {
const createSource = (content: string) => ({
source: () => content,
size: () => Buffer.byteLength(content),
});

const built = await build({ '/src/index.js': '' }, (config) => {
configureEsbuildMinifyPlugin(config);

config.plugins!.push({
apply(compiler) {
compiler.hooks.compilation.tap('test', (compilation) => {
compilation.hooks.processAssets.tap(
{ name: 'test' },
() => {
compilation.emitAsset(
'test.js',
createSource(' 1 + 1'),
);
},
);
});
},
});
}, webpack5);

expect(built.stats.hasWarnings()).toBe(false);
expect(built.stats.hasErrors()).toBe(false);

expect(Object.keys(built.stats.compilation.assets)).toStrictEqual([
'index.js',
'test.js',
]);
expect(
built.fs.readFileSync('/dist/test.js', 'utf8'),
).toBe('1+1;\n');
});
});
});

0 comments on commit f5bc714

Please sign in to comment.