sourcemap for bundle

This commit is contained in:
pavletto 2025-05-02 10:48:26 +04:00
parent fdd705abfe
commit 015c4e3780
2 changed files with 32 additions and 14 deletions

View File

@ -1,26 +1,43 @@
import { readFile, writeFile } from 'fs/promises'; import { readFile, writeFile } from 'fs/promises';
import path from 'node:path';
import { minify } from 'terser'; import { minify } from 'terser';
export default function forceTerserPlugin({ filePath }) { export default function forceTerserPlugin({ filePath }) {
const mapPath = `${filePath}.map`;
const fileName = path.basename(filePath);
const mapFileName = path.basename(mapPath);
return { return {
name: 'vite-plugin-force-terser', name: 'vite-plugin-force-terser',
apply: 'build', apply: 'build',
closeBundle: async () => { async closeBundle() {
const code = await readFile(filePath, 'utf-8'); const [code, prevMap] = await Promise.all([
readFile(filePath, 'utf-8'),
readFile(mapPath, 'utf-8')
]);
const result = await minify(code, { const result = await minify(
{ [fileName]: code },
{
compress: true, compress: true,
mangle: true, mangle: true,
format: { format: { comments: false },
comments: false sourceMap: {
content: prevMap,
filename: fileName,
url: mapFileName
} }
}); }
);
if (result.code) { if (result.code && result.map) {
await writeFile(filePath, result.code, 'utf-8'); await Promise.all([
console.log(`${filePath} minified with terser`); writeFile(filePath, result.code, 'utf-8'),
writeFile(mapPath, result.map, 'utf-8'),
]);
console.log(`${fileName} and ${mapFileName} regenerated with Terser`);
} else { } else {
console.warn('⚠ terser did not return any code'); console.warn('⚠ terser did not return code or map');
} }
} }
}; };

View File

@ -26,11 +26,12 @@ export default function ({mode}: { mode: 'development' | 'production' }) {
}, },
emptyOutDir: true, emptyOutDir: true,
outDir: path.resolve(__dirname, './lib'), outDir: path.resolve(__dirname, './lib'),
sourcemap: isDev, sourcemap: true,
rollupOptions: { rollupOptions: {
output: { output: {
entryFileNames: `og.[format].js`, entryFileNames: `og.[format].js`,
assetFileNames: `[name][extname]` assetFileNames: `[name][extname]`,
sourcemapExcludeSources: true,
}, },
plugins: [ plugins: [
// doesn't work for esm modules // doesn't work for esm modules