Skip to content
This repository has been archived by the owner on Jul 29, 2022. It is now read-only.

Commit

Permalink
Simplify assets discarding
Browse files Browse the repository at this point in the history
It looks like ViteJS 2.5.0 fixed a compatibility problem with Rollup (probably this: vitejs/vite#4352) wich makes bundle entries to have a correct name, which drastically simplify the process of finding a corresponding transformed modules.
  • Loading branch information
lucsky committed Aug 20, 2021
1 parent fd9c83a commit c6db9ab
Showing 1 changed file with 6 additions and 17 deletions.
23 changes: 6 additions & 17 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import fs from 'fs';
import path from 'path';
import esbuild from 'esbuild';

import type { Plugin } from 'vite';
Expand Down Expand Up @@ -30,26 +29,16 @@ export default function svgrPlugin(): Plugin {

generateBundle(config, bundle) {
// Discard transformed SVG assets from bundle so they are not emitted
const patterns = transformed.map((id) => {
const basename = path.basename(id, '.svg?component');
return fileNamePatternToRegExp(config.assetFileNames, basename);
});

for (const [key, bundleEntry] of Object.entries(bundle)) {
const { type, fileName } = bundleEntry;
if (type === 'asset' && fileName.endsWith('.svg') && patterns.some((p) => fileName.match(p))) {
const { type, name } = bundleEntry;
if (
type === 'asset' &&
name?.endsWith('.svg') &&
transformed.findIndex((id) => id.includes(name)) >= 0
) {
delete bundle[key];
}
}
}
};
}

function fileNamePatternToRegExp(pattern: string, name: string) {
const regexp = pattern
.replace('[name]', name)
.replace('[hash]', '[a-z0-9]+')
.replace('[ext]', 'svg')
.replace(/\./g, '\\.');
return new RegExp(regexp);
}

0 comments on commit c6db9ab

Please sign in to comment.