Skip to main content
Module

x/lume/plugins/terser.ts

πŸ”₯ Static site generator for Deno πŸ¦•
Very Popular
Go to Latest
File
import { minify } from "../deps/terser.ts";import { basename } from "../deps/path.ts";import { Exception, merge } from "../core/utils.ts";import { Helper, Page, Site } from "../core.ts";
export interface Options { /** The list of extensions this plugin applies to */ extensions: string[];
/** Set `true` to generate source map files */ sourceMap: boolean;
/** Options passed to `terser` */ options: Partial<TerserOptions>;}
/** Terser options */export interface TerserOptions { /** Use when minifying an ES6 module. */ module: boolean;
/** To compress the code */ compress: boolean;
/** Pass false to skip mangling names */ mangle: boolean;
/** To generate a source map */ sourceMap?: { filename: string; url: string; };}
// Default optionsconst defaults: Options = { extensions: [".js"], sourceMap: false, options: { module: true, compress: true, mangle: true, },};
/** A plugin to load all JavaScript files and minify them using Terser */export default function (userOptions?: Partial<Options>) { const options = merge(defaults, userOptions);
return (site: Site) => { site.loadAssets(options.extensions); site.process(options.extensions, terser); site.filter("terser", filter as Helper, true);
async function terser(file: Page) { const filename = file.dest.path + file.dest.ext; const content = file.content; const terserOptions = { ...options.options };
if (options.sourceMap) { terserOptions.sourceMap = { filename, url: basename(filename) + ".map", }; }
try { const output = await minify({ [filename]: content }, terserOptions); file.content = output.code;
if (output.map) { const mapFile = file.duplicate(); mapFile.content = output.map; mapFile.dest.ext = ".js.map"; site.pages.push(mapFile); } } catch (err) { throw new Exception( "Plugin terser: Error processing the file", { page: file }, err, ); } }
async function filter(code: string) { const output = await minify(code, options.options); return output.code; } };}